Webber Depor
Webber Depor

Reputation: 198

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?

Upvotes: 4

Views: 2361

Answers (3)

trincot
trincot

Reputation: 350137

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()

Upvotes: 3

Fin
Fin

Reputation: 386

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);
        }
    }
}

Upvotes: 1

davmos
davmos

Reputation: 9577

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

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

Upvotes: 3

Related Questions