[英]I have the javascript code getElementsByClassName how it will be on php?
i have this code on javascript我在 javascript 上有这个代码
String(document.getElementsByClassName('ord-total-val')[0].innerText).substr(0,3)
this cod grab class element 'ord-total-val', and returns its text string to me.这条鳕鱼抓取 class 元素“ord-total-val”,并将其文本字符串返回给我。 I try this:
我试试这个:
$classname="blockProduct";
$finder = new DomXPath($doc);
$spaner = $finder->query("//*[contains(@class, '$classname')]");
But my knowledge is not enough to complete it.但我的知识不足以完成它。 Can you help my to write this stroke on php?
你能帮我在 php 上写下这个笔画吗?
To be fair your code is virtually complete and appears to work OK when I combined it with a basic test case.公平地说,您的代码实际上是完整的,并且当我将它与基本测试用例结合使用时,它似乎可以正常工作。
<?php
$strhtml="<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<style></style>
<script></script>
</head>
<body>
<p>wibble wobble</p>
<div class='blockProduct'>whoohoo! Some text</div>
<p>lorem ipsum dolor solit...</p>
<span class='blockProduct'>and even more text in a different HTML element</span>
</body>
</html>";
$className='blockProduct';
$dom=new DOMDocument;
$dom->loadHTML($strhtml);
$xp=new DOMXPath($dom);
$expr='//*[ contains( @class, "'.$className.'" ) ]';
$col=$xp->query( $expr );
if( $col && $col->length > 0 ){
foreach( $col as $node ){
$text=$node->nodeValue;
$substr=substr($text,0,3);
echo $substr . '<br />';
}
}
?>
Given the HTML source above this will output:鉴于上面的 HTML 源代码,这将是 output:
who
and
Using your code, but modified just slightly to use the XPath object already created, $xp
:使用您的代码,但稍作修改以使用 XPath object 已经创建,
$xp
:
$spaner = $xp->query("//*[contains(@class, '$className')]");
This gives a nodelist
so you need to iterate through this nodelist
to show the contents.这给出了一个
nodelist
,因此您需要遍历此nodelist
以显示内容。
foreach($spaner as $span)echo $span->nodeValue;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.