Home > Article > Backend Development > How to Extract Inner XML Content from a SimpleXMLElement Without the Wrapping Tags in PHP?
When extracting the inner HTML contents of an element using PHP's SimpleXMLElement class, the asXML() method returns the entire element, including its wrapping tags. To obtain just the inner XML, a custom function is required.
One such function is presented 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>
For instance, given 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>
To extract the inner XML of the answer element:
<code class="php">$xml = simplexml_load_string($xml_string); $answer_innerXML = SimpleXMLElement_innerXML($xml->answer);</code>
$answer_innerXML will contain the string:
Who who, <strong>who who</strong>, <em>me</em>
The above is the detailed content of How to Extract Inner XML Content from a SimpleXMLElement Without the Wrapping Tags in PHP?. For more information, please follow other related articles on the PHP Chinese website!