A
B
C' $dom = new DOMDocument; @$dom->loadHTML($html); $xp = new DOMX" /> A
B
C' $dom = new DOMDocument; @$dom->loadHTML($html); $xp = new DOMX" /> A
B
C' $dom = new DOMDocument; @$dom->loadHTML($html); $xp = new DOMX"/>

DOMXPath query check for div if it exists

869 views Asked by At

I have this code:

$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")]');

I want to make the DOMXPath query select the <div> element with class = "container" but i want it only to select the <div class="wrapper"></div> when it exists. So i want it to select <div class="container"> when <div class="wrapper"> doesn't exist, but when it does i want it to only select <div class="wrapper">.

Thanks in advance.

1

There are 1 answers

1
pes502 On

As first, you can count all <div class="wrapper"> elements via:

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

if this returns int(0) it means, that no element with wrapper class has been found. With these information, we can easily modify your code to something like this:

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