2011-05-26 120 views
3

我得到了上面的錯誤,並試圖打印出對象,看我怎麼可以訪問它裏面的數據,但它只是呼應的DOMNodeList對象()對象無法轉換爲字符串

function dom() { 
$url = "http://website.com/demo/try.html"; 
$contents = wp_remote_fopen($url); 

$dom = new DOMDocument(); 
@$dom->loadHTML($contents); 
$xpath = new DOMXPath($dom); 

$result = $xpath->evaluate('/html/body/table[0]'); 
print_r($result); 
    } 

我使用WordPress的,從而解釋了wp_remote_fopen功能。我試圖回顯第一個表$ url

回答

13

是的,DOMXpath::query返回總是一個DOMNodeList,這是一個奇怪的對象有點處理。基本上,你必須遍歷它,或者只是使用item()拿到一個項目:

// There's actually something in the list 
if($result->length > 0) { 
    $node = $result->item(0); 
    echo "{$node->nodeName} - {$node->nodeValue}"; 
} 
else { 
    // empty result set 
} 

或者你可以遍歷值:

foreach($result as $node) { 
    echo "{$node->nodeName} - {$node->nodeValue}"; 
    // or you can just print out the the XML: 
    // $dom->saveXML($node); 
} 
+1

謝謝,真正幫助我的理解! – Ryan 2011-05-26 17:19:29

0

的Xpath從1開始不爲0的指數:/html/body/table[1]

現在如果你想保存匹配的節點的HTML或者,如果你想節點的文本內容看情況。

$html = <<<'HTML' 
<html> 
    <body> 
    <p>Hello World</p> 
    </body> 
</html> 
HTML; 

$dom = new DOMDocument(); 
$dom->loadHTML($html); 
$xpath = new DOMXPath($dom); 

// iterate all matched nodes and save them as HTML to a buffer 
$result = ''; 
foreach ($xpath->evaluate('/html/body/p[1]') as $p) { 
    $result .= $dom->saveHtml($p); 
} 
var_dump($result); 

// cast the first matched node to a string 
var_dump(
    $xpath->evaluate('string(/html/body/p[1])') 
); 

演示:https://eval.in/155592

string(18) "<p>Hello World</p>" 
string(11) "Hello World"