PHP SimpleXML: Accessing Inner XML
In the realm of PHP XML parsing, the SimpleXML extension allows developers to manipulate XML documents with ease. However, extracting the inner contents of an XML element, excluding the surrounding element tags, can be challenging.
Consider the following XML snippet:
Who are you? Who who, who who, me
To retrieve just the contents of the "answer" element (i.e., "Who who, who who, me"), we need to bypass the default asXML() method. Instead, we introduce an elegant solution using the dom_import_simplexml() function.
function SimpleXMLElement_innerXML($xml)
{
$innerXML = '';
foreach (dom_import_simplexml($xml)->childNodes as $child)
{
$innerXML .= $child->ownerDocument->saveXML( $child );
}
return $innerXML;
}
By employing this function, we can access the inner XML of any element:
$xml = simplexml_load_string($xmlString);
$innerAnswer = SimpleXMLElement_innerXML($xml->answer);
The resulting $innerAnswer variable will contain the desired string: "Who who, who who, me". This approach preserves the original formatting and character entities within the inner XML, making it ideal for maintaining the integrity of the extracted content.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3