2013-05-26 52 views
3

我使用PHP的DomDocument并试图刮出来的东西,看起来像这样:获取有itemprop的属性的所有元素

<div itemprop='movie'>Fight Club</div> 

它也可能是这样的:

<span itemprop='musician'>Ozzy Osbourne</span> 

我想抓取页面上的所有itemprop='n',并将它们放入数组中以存储它们的nodevalue以及相关的itemprop名称。到目前为止我的代码看起来是这样的:

function getItemprops(){ 
     foreach($this->dom->getAttribute("itemprop") as $buffer) { 
       $itempropList = array(
        'theNodeValue' => $buffer->nodeValue, 
        'theItemprop' => $buffer->getAttribute("itemprop") 
       ) 
       return $itempropList; 
     } 
} 

我的代码应该沿线的某处得到一个数组:

array (
     array(
     0 => 
       "theNodeValue" => "Fight Club", 
       "theItemprop" => "movie" 
     1 => 
       "theNodeValue" => "Fight Club", 
       "theItemprop" => "movie" 
    ) 
) 

不幸的是,我的代码返回Fatal error: Call to undefined method DOMDocument::getAttribute()

所以基本上,我想选择所有itemprop=""的并将它们放入数组中。

感谢您的帮助!

回答

3

您需要先使用XPath选择具有您所需属性的所有节点,然后循环返回的节点以获取文本值和属性值;像这样

$d = new DOMDocument(); 
$d->loadHTML($xmlsource); 
$xpath = new DOMXPath($d); 
$nodes = $xpath->query('//*[@itemprop]'); //this catches all elements with itemprop attribute 
foreach ($nodes as $node) { 
    // do your stuff here with $node 
+0

非常感谢! –