2015-11-03 56 views
0

我想从html中抓取一些元素,但是我无法根据需要刮取数据。Php Dom文档结果错误

HTML

<div class="opinions"> 
<ul> 
<li> 
<div class="imgcontainers"> 
<a href="domainname.com" title="title">             `<img width="160" src="image.jpg" />` 
</a> 
</div> 
<p class="caption"> 
<a href="domainname.com" class="head">asdfad</a> 
<span>November 03, 2015 09:29 This is article title</span> 
</p> 
</li> 
</ul> 
</div> 
$dom = new DOMDocument(); 
$classname = 'opinions'; 
$html = get_page($url); 
@$dom->loadHTML($html); 
$dom->preserveWhiteSpace = false; 
$xpath = new DOMXPath($dom); 
$articles = $xpath->query("//*[@class='" . $classname . "']"); 

$p = $articles->getElementsByTagName('a'); 
$div = $articles->getElementsByTagName('div'); 
foreach($p as $value){ 
    $title = $value->getAttribute("href"); 
    echo $title; 
} 

当我运行该脚本,我得到这个错误“调用未定义的方法的DOMNodeList ::的getElementsByTagName()”

我究竟需要的是,我需要每一个HREF链接和img src路径(如果有)和span文本值。请建议您的建议如何实现这一点。

回答

0

也许你可以从我的code

学到一些东西或者,如果你决定,包括我的功能,这里是我如何做到这一点:

$html = ""; //your html 
    $props = array(
    array("tagname"=>"div", "props"=>array("class"=>"opinions")), 
    //the '/' before 'a' is for all descendant <a> of <div> 
    array("tagname"=>"/a"), 
    ); 
    $options = array("property"=>"href"); 
    require_once 'getNodeValue.php'; 
    $hrefs = getNodeValue($html, $props, $options); 
    print_r($hrefs);