Home >Backend Development >PHP Tutorial >How to Extract Inner XML Content from SimpleXMLElement in PHP?
PHP SimpleXML: Accessing Inner XML
In XML manipulation with PHP's SimpleXML, it is often necessary to retrieve the inner HTML content of an element without the enclosing tag. This article explores how to achieve this using SimpleXML.
Consider the following XML structure:
<code class="xml"><qa> <question>Who are you?</question> <answer>Who who, <strong>who who</strong>, <em>me</em></answer> </qa></code>
To extract the inner content of the "answer" element as a string, the following methods are available:
Using asXML():
<code class="php">$answer = new SimpleXMLElement($xml); $innerXML = $answer->asXML(); // Returns "<answer>Who who, <strong>who who</strong>, <em>me</em></answer>"</code>
Using DOMDocument:
<code class="php">$answer = new SimpleXMLElement($xml); $dom = dom_import_simplexml($answer); $innerXML = $dom->ownerDocument->saveXML($dom); // Returns "Who who, <strong>who who</strong>, <em>me</em>"</code>
Using a Custom Function:
The following custom function can be defined to extract inner XML:
<code class="php">function SimpleXMLElement_innerXML($xml) { $innerXML = ''; foreach (dom_import_simplexml($xml)->childNodes as $child) { $innerXML .= $child->ownerDocument->saveXML($child); } return $innerXML; }</code>
Using this function:
<code class="php">$innerXML = SimpleXMLElement_innerXML($answer); // Returns "Who who, <strong>who who</strong>, <em>me</em>"</code>
These methods provide options to extract the inner XML of SimpleXML elements, enabling efficient manipulation and retrieval of XML content.
The above is the detailed content of How to Extract Inner XML Content from SimpleXMLElement in PHP?. For more information, please follow other related articles on the PHP Chinese website!