选择多个类名,并使用PHP DOMXpath在该类中获取子节点

时间:2016-03-06 19:35:54

标签: php domdocument 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>

这是我要解析和获取内容的HTML。我想要text node inside <i> tag。我正在使用DOMDocumentDOMXpath

$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?

3 个答案:

答案 0 :(得分:2)

您可以使用以下XPath查询执行所有操作:

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

MDN on starts-with

  

starts-with检查第一个字符串是否以第二个字符串开头并返回true或false。

如果您对这些行中的所有文本节点感兴趣,那么b标记中的文本节点以及可能在这些行中的任何其他标记也是如此,那么请使用双斜杠:

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

我不熟悉XPath,因此我使用<div>循环遍历每个DOMDocument()元素。检查它是否具有值为row-0或row-1的属性类。如果是,则获取每个元素<i>并转储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);
        }
    }
}