XPath savehtml remove parent element

I want to get HTML inside the parent element. For example, I have this structure:

<div> <div>text<b>more text</b>and <i>some more</i></div> </div> 

and I want to get text<b>more text</b>and <i>some more</i> as a result.

Here is my code:

 $dom = new DOMDocument(); $dom->loadhtml($html); $xpath = new DOMXPath($dom); $text = $xpath->query("//div/div"); $html = $dom->saveHTML($text->item(0)); 

And the result

 <div>text<b>more text</b>and <i>some more</i></div> 

I thought about using preg_replace, but this is not a good idea. How to remove a parent using XPath?

0
source share
2 answers

You may need

 $html = ''; foreach ($text->item(0)->childNodes as $child) { $html .= $dom->saveHTML($child); } 

This pseudo code, iterating over the child nodes of a div node element, I hope I got the PHP syntax correctly.

0
source

Instead of looking at your problem to remove the parent (who is faced with the problematic output and then thinking that you need to delete something), just rotate it 180 ° around and don't add it in the first place. This is the HTML preservation of all the child nodes of this div.

First, the xpath expression for all child nodes //div/div :

 //div/div/node() 

This means that some type of node is requested in xpath, so not only the node elements, but also the text nodes that you need here.

So now you want to use $dom->saveHTML() for all of these nodes. This can be done by matching the call to this function with all of these elements:

 $inner = $xpath->query("//div/div/node()"); $html = implode('', array_map([$dom, 'saveHTML'], iterator_to_array($inner))); 

This will do $html following:

 text<b>more text</b>and <i>some more</i> 

Instead of matching, you can also use a bit more detailed code, which is probably easier to read:

 $inner = $xpath->query("//div/div/node()"); $html = ''; foreach($inner as $node) { $html .= $dom->saveHTML($node); } 

Compared to the previous answer, you can see it similar, but a bit more simplified, because it uses the xpath expression to query elements for saving directly.

+1
source

Source: https://habr.com/ru/post/890884/


All Articles