Home >Backend Development >PHP Tutorial >How to Extract Inner XML Content from a SimpleXMLElement in PHP?

How to Extract Inner XML Content from a SimpleXMLElement in PHP?

DDD
DDDOriginal
2024-11-01 16:00:31947browse

How to Extract Inner XML Content from a SimpleXMLElement in PHP?

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:

<qa>
  <question>Who are you?</question>
  <answer>Who who, <strong>who who</strong>, <em>me</em></answer>
</qa>

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.

<code class="php">function SimpleXMLElement_innerXML($xml)
  {
    $innerXML = '';
    foreach (dom_import_simplexml($xml)->childNodes as $child)
    {
        $innerXML .= $child->ownerDocument->saveXML( $child );
    }
    return $innerXML;
  }</code>

By employing this function, we can access the inner XML of any element:

<code class="php">$xml = simplexml_load_string($xmlString);
$innerAnswer = SimpleXMLElement_innerXML($xml->answer);</code>

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.

The above is the detailed content of How to Extract Inner XML Content from a SimpleXMLElement in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn