简体   繁体   中英

Choose multiple class name and get childnode inside that class with PHP DOMXpath

<div id="conti">
  <div class="no_matter"></div>
  <div class="row-0">
    <b></b>
    <span>
      <i>"child node that i want to get"</i>
    </span>
  </div>

  <div class="row-1">
    <b></b>
    <span>
      <i>"child node that i want to get"</i>
    </span>
  </div>

  <div class="row-0">
    <b></b>
    <span>
      <i>"child node that i want to get"</i>
    </span>
  </div>

  <div class="row-1">
    <b></b>
    <span>
      <i>"child node that i want to get"</i>
    </span>
  </div>

  ...
  ...
  class row-0 and row-1 repeats itself
  ...
  ...

</div>

This is the HTML that i want to parse and get contents. I want text node inside <i> tag . I am using DOMDocument and DOMXpath

$dom = new DOMDocument();
$dom->loadHTMLFile('http://www.meal.org/anter.php');
$dom->preserveWhiteSpace = true;

$xpath = new DOMXPath($dom);

$row = $xpath->query('//*[@class="row-0" ]');  //my problem begins there. I want both 'row-0' and 'row-1'. How i am gonna choose multiple class?

//and than how i am gonna get `<i>` tag inside every `row-0` and `row-1` class and get the text node?

You can do all that with the following XPath query:

//*[starts-with(@class,"row-")]/span/i/text()

MDN on starts-with :

The starts-with checks whether the first string starts with the second string and returns true or false.

If you are interested in all text nodes in these rows, so also the ones in the b tags, and any other tags that might be in those rows, then use the double slash:

//*[starts-with(@class,"row-")]//text()
$iTags = $xpath->query('//div[@class="row-0" or @class="row-1"]/span/i');

foreach ($iTags as $iTag) {
    var_dump(trim($iTag->nodeValue));
}

I'm not fammiliar with XPath, so I'm looping trough each <div> element using DOMDocument() . Check wheter it has a attribute class with value row-0 or row-1. If so then get each element <i> and dump the nodeValue.

foreach($dom->getElementsByTagName('div') as $div){
    if($div->getAttribute('class') == 'row-0' OR $div->getAttribute('class') == 'row-1'){
        foreach($div->getElementsByTagName('i') as $i){
            var_dump($i->nodeValue);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM