2013-05-26 47 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

非常感謝! –