[英]php domdocument get node info
我正在使用php,正在嘗試從網頁中獲取某些數據
一切正常,直到我進入這一部分:
<a class="cleanthis" href="https://www.web.com" id="1122" rel="#1122" style="display: inline-block;"><strong>the data i want</strong></a>
如您所見,我想要強大的數據,但我無法獲取。 我只有空白行
我使用的代碼:
foreach($as as $a) {
if ($a->getAttribute('class') === 'cleanthis') {
$strong = $a->getElementsByTagName('strong');
echo $strong->nodeValue;;
}
您應該會看到以下錯誤消息:
未定義的屬性:DOMNodeList :: $ nodeValue
那是因為$strong = $a->getElementsByTagName('strong');
會將DOMNodeList
放在$string
。 您需要迭代列表或從列表中檢索實際節點,例如
echo $strong->item(0)->nodeValue;
或者,您可以只使用XPath:
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
foreach ($xpath->evaluate('//a[@class="cleanthis"]/strong/text()') as $element) {
echo $element->nodeValue, PHP_EOL;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.