2014-12-02 57 views
1

我試圖讀取HTML字符串像下面的H1值,PHP DOMDocument和getElementsByTagName問題?

<h1> 
<a href="http://example.com/?p=5016"> love me for a reason </a> 
</h1> 

我使用下面的代碼,但它返回空值的標題,但內容似乎工作(下一行)?爲什麼

libxml_use_internal_errors(true); 
$dom_document = new DOMDocument(); // CREATE A NEW DOCUMENT 
$dom_document->loadHTML(mb_convert_encoding($row['html'], 'HTML-ENTITIES', 'UTF-8')); // LOAD THE STRING INTO THE DOCUMENT 

$article_titles=$dom_document->getElementsByTagName("h1"); 
$title = $article_titles->textContent; 


//this works fine 
$article_contents=$dom_document->getElementByID("article-single"); 
$content=$article_contents->textContent; 
libxml_use_internal_errors(false); 

回答

2

標題內容是空的,因爲$article_titles仍然是一個DOMNodeList。由於您獲取的元素爲標籤名稱您會期望這會返回一個或多個元素,而不是通過獲取元素id,您只需要預期一個元素,因爲它們應該是唯一的。

您必須定位DOMElement才能獲得->textContent值。您可以直通鏈接->item(index_num)實現它:

$article_titles = $dom_document->getElementsByTagName("h1"); // DOMNodeList 
$title = $article_titles->item(0)->textContent; 
         //^point to the first item found, it starts at zero 
echo $title; 

如果你想使用foreach

foreach($dom_document->getElementsByTagName("h1") as $title) { 
    echo $title->textContent . '<br/>'; 
} 
+0

可以請你加入的for-each循環也套內有人需要遍歷所有的項目,不只是一個。 – mahen3d 2014-12-03 00:08:32

+0

@ mahen3d當然,我在答案中添加了一個循環 – Ghost 2014-12-03 00:11:06

相關問題