Home >Backend Development >PHP Tutorial >How to Fetch Inner XML with PHP SimpleXML?
When working with XML data, extracting specific parts can be crucial. One common task is obtaining the inner HTML of an element, excluding the element's tags. This article explores how to accomplish this using PHP SimpleXML.
Consider the following XML:
<code class="xml"><qa> <question>Who are you?</question> <answer>Who who, <strong>who who</strong>, <em>me</em></answer> </qa></code>
Our goal is to retrieve the inner HTML of the "answer" element, which is:
<code class="html">Who who, <strong>who who</strong>, <em>me</em></code>
PHP does not provide a built-in method to access the inner XML of an element. However, custom functions can be created to fulfill this need. One such function, SimpleXMLElement_innerXML, is defined below:
<code class="php">function SimpleXMLElement_innerXML($xml) { $innerXML = ''; foreach (dom_import_simplexml($xml)->childNodes as $child) { $innerXML .= $child->ownerDocument->saveXML( $child ); } return $innerXML; }</code>
This function leverages the PHP DOM extension to convert our SimpleXMLElement ($xml) into a DOMNode object. It then iterates over its child nodes, saving each node's XML representation into the $innerXML string. Finally, $innerXML holds the element's inner HTML.
To use the SimpleXMLElement_innerXML function, we can write:
<code class="php">$xml = simplexml_load_string('<qa><answer>Who who, <strong>who who</strong>, <em>me</em></answer></qa>'); $innerXML = SimpleXMLElement_innerXML($xml->answer); echo $innerXML; // Outputs: Who who, <strong>who who</strong>, <em>me</em></code>
With the SimpleXMLElement_innerXML function, retrieving the inner XML of an element becomes straightforward. By leveraging the DOM extension, we gain precise control over XML manipulation.
The above is the detailed content of How to Fetch Inner XML with PHP SimpleXML?. For more information, please follow other related articles on the PHP Chinese website!