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

DDD
Release: 2024-11-01 16:00:31
Original
862 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!