Question

I'm trying to access the parentNode of an element found with preg_match, because I would like to read the result found with regex through the DOM of the document. I can't access it directly through PHP's DOMDocument because the amount of div's is variable and they have no actualy ID or any other attribute that is able to match.

To illustrate this: in the below example I'd match match_me with preg_match, and then I'd want to access the parentNode (div) and put all the child elements (the p's) in an DOMdocument object, so I can easily display them.

   <div> 
   .... variable amount of divs
   <div>
   <div>
       <p>1 match_me</p><p>2</p>
   </div>
   </div>
   </div>
Était-ce utile?

La solution

Use DOMXpath to query for the node by the value of its child:

$dom = new DOMDocument();
// Load your doc however necessary...

$xpath = new DOMXpath($dom);

// This query should match the parent div itself
$nodes = $xpath->query('/div[p/text() = "1 match_me"]');
$your_div = $nodes->item(0);
// Do something with the children
$p_tags = $your_div->childNodes;


// Or in this version, the query returns the `<p>` on which `parentNode` is called
$ndoes = $xpath->query('/p[text() = "1 match_me"]');
$your_div = $nodes->item(0)->parentNode;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top