Getting Inner XML Content with SimpleXML in PHP
When working with XML data in PHP, you may encounter a situation where you need to extract the inner content of an element, excluding the element tags themselves. This can be achieved with the help of XPath queries or custom functions.
Custom Function Approach:
One efficient method to obtain the inner XML content is to create a custom function that iterates through the nodes and extracts the required data.
<code class="php">function SimpleXMLElement_innerXML($xml) { $innerXML = ''; foreach (dom_import_simplexml($xml)->childNodes as $child) { $innerXML .= $child->ownerDocument->saveXML($child); } return $innerXML; }</code>
Usage:
<code class="php">$xml = '<qa> <question>Who are you?</question> <answer>Who who, <strong>who who</strong>, <em>me</em></answer> </qa>'; $answer = simplexml_load_string($xml); $inner_content = SimpleXMLElement_innerXML($answer); echo $inner_content; // Output: "Who who, <strong>who who</strong>, <em>me</em>"</code>
Conclusion:
This custom function provides a straightforward and efficient way to retrieve the inner XML content of SimpleXMLElement objects, without resorting to complex string manipulation techniques. It is particularly useful when handling large or complex XML structures.
The above is the detailed content of How to extract the inner XML content of a SimpleXMLElement object in PHP?. For more information, please follow other related articles on the PHP Chinese website!