Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 858
Webber Depor Avatar asked Mar 13 '23 01:03

Webber Depor


2 Answers

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()
like image 166
trincot Avatar answered Mar 18 '23 21:03

trincot


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

foreach ($iTags as $iTag) {
    var_dump(trim($iTag->nodeValue));
}
like image 42
davmos Avatar answered Mar 18 '23 22:03

davmos