html - PHP DOMDocument and getElementsByTagName questions? -
i trying read h1 value html string below,
<h1> <a href="http://example.com/?p=5016"> love me reason </a> </h1>   i using following code returns empty value title content seems working (next line) ? why
libxml_use_internal_errors(true); $dom_document = new domdocument(); // create new document $dom_document->loadhtml(mb_convert_encoding($row['html'], 'html-entities', 'utf-8')); // load string 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);      
the title content empty because $article_titles still domnodelist. since getting elements tag name expect return 1 or more element opposed getting elements id, expecting 1 since supposed unique. 
you must target domelement ->textcontent value. can reach thru chaining ->item(index_num):
$article_titles = $dom_document->getelementsbytagname("h1"); // domnodelist $title = $article_titles->item(0)->textcontent;                        //  ^ point first item found, starts @ 0 echo $title;   if want use foreach:
foreach($dom_document->getelementsbytagname("h1") $title) {     echo $title->textcontent . '<br/>'; }      
Comments
Post a Comment