使用DOMdocument()方法通过ClassName获取元素 [英] Get Element by ClassName with DOMdocument() Method
问题描述
这是我想实现:检索页面上的所有产品,并将它们放入数组。这里是我使用的代码:
Here is what I am trying to achieve : retrieve all products on a page and put them into an array. Here is the code I am using :
$page2 = curl_exec($ch);
$doc = new DOMDocument();
@$doc->loadHTML($page2);
$nodes = $doc->getElementsByTagName('title');
$noders = $doc->getElementsByClassName('productImage');
$title = $nodes->item(0)->nodeValue;
$product = $noders->item(0)->imageObject.src;
它适用于 $ title,但
为产品。有关信息,在HTML代码中,img标签如下所示:
It works for the $title but
not for the product. For info, in the HTML code the img tag looks like this :
<img alt="" class="productImage" data-altimages="" src="xxxx">
我一直在看这个( PHP DOMDocument如何获取元素?)但是我还是不明白如何使它工作。
I have been looking at this (PHP DOMDocument how to get element?) but I still don't understand how to make it work.
PS:我收到此错误:
PS : I get this error :
调用未定义的方法
DOMDocument :: getElementsByclassName )
Call to undefined method
DOMDocument::getElementsByclassName()
推荐答案
我最后使用以下解决方案: p>
I finally used the following solution :
$classname="blockProduct";
$finder = new DomXPath($doc);
$spaner = $finder->query("//*[contains(@class, '$classname')]");
这篇关于使用DOMdocument()方法通过ClassName获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!