php - DOMDocument, get the text in an element that follow a found element -


i'd text ul>li follows text abc. text in case 123.

<h2>cde</h2> <ul>...</ul>  <h2>abc</h2> <ul>   <li>     <span>123</span>   </li> </ul> 

this have, it's not working

$dom = new domdocument(); $dom->loadhtml($html); // $html code above  $h2_all = $dom->getelementsbytagname('h2');  foreach($h2_all $h2) {   $h2_text = $h2->textcontent;    if (trim(strtolower($h2_text)) == 'abc') {     var_dump($h2->nextsibling);   } } 

i assume it's because $h2 doesn't contain ul data need, i'm not sure how it.

you can use xpath query:

$dom = new domdocument; $dom->loadhtml($html);  $xp = new domxpath($dom);  $qry = '//ul[preceding::h2[1] = "abc"]/li/span';  $result = $xp->query($qry)->item(0)->nodevalue; 

query details:

//         # path can start anywhere in dom tree ul [preceding::h2[1] = "abc"] # condition: first preceding h2 has value "abc" /li/span   # lets continue path until span node 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -