如果div存在,则对DOM进行DOMXPath查询检查

时间:2018-06-16 15:23:36

标签: php domxpath

我有这段代码:

$html = '<div class="container">A<div class="wrapper">B</div>C</div>'

$dom = new DOMDocument;
@$dom->loadHTML($html);

$xp = new DOMXPath($dom);

$links = $xp->query('//div[contains(@class,"container")]');

我想让DOMXPath查询选择带有<div>的{​​{1}}元素,但我希望它仅在存在时选择class = "container"。所以我希望它在<div class="wrapper"></div>不存在时选择<div class="container">,但是当它确实存在时,我希望它只选择<div class="wrapper">

提前致谢。

1 个答案:

答案 0 :(得分:0)

首先,您可以通过以下方式计算所有<div class="wrapper">元素:

$wrapper = $xp->query('//div[contains(@class,"wrapper")]')->length;

如果返回 int(0)则表示没有找到wrapper类的元素。有了这些信息,我们可以轻松地将您的代码修改为:

$html = '<div class="container">A<div class="wrapper">B</div>C</div>';

$dom = new DOMDocument;
@$dom->loadHTML($html);

$xp = new DOMXPath($dom);

$wrapper = $xp->query('//div[contains(@class,"wrapper")]');

if($wrapper->length == 0) {
  // wrapper class NOT FOUND, now we can select container class
  $links = $xp->query('//div[contains(@class,"container")]');  
}

else {
  // 1 or MORE wrapper class FOUND, do something with your .wrapper class   
}