我有使用以下代码的HTML网页:
<div class="col-sm-9 xs-box2">
<h2 class="title-medium br-bottom">Your Name</h2>
</div>
现在,我想使用简单HTML DOM解析器在此div中获取h2的文本值。 我的代码是:
$name = $html->find('h2[class="title-medium br-bottom"]');
echo $name;
但是它总是返回错误:“
Notice: Array to string conversion in C:\xampp\htdocs\index.php on line 21
Array
如何解决此错误?
答案 0 :(得分:1)
您可以尝试Simple HTML DOM
foreach($html->find('h2') as $element){
$element->class;
}
还有其他解析方法
方法1。
您可以使用以下代码段,H2
和DOMDocument
来获得getElementsByTagName
标记
$received_str = '<div class="col-sm-9 xs-box2">
<h2 class="title-medium br-bottom">Your Name</h2>
</div>';
$dom = new DOMDocument;
@$dom->loadHTML($received_str);
$h2tags = $dom->getElementsByTagName('h2');
foreach ($h2tags as $_h2){
echo $_h2->getAttribute('class');
echo $_h2->nodeValue;
}
方法2
使用Xpath
可以对其进行解析
$received_str = '<div class="col-sm-9 xs-box2">
<h2 class="title-medium br-bottom">Your Name</h2>
</div>';
$dom = new DOMDocument;
$dom->loadHTML($received_str);
$xpath = new DomXPath($dom);
$nodes = $xpath->query("//h2[@class='title-medium br-bottom']");
header("Content-type: text/plain");
foreach ($nodes as $i => $node) {
$node->nodeValue;
}