How to Extract Inner XML Content from a SimpleXMLElement Without the Wrapping Tags in PHP?

Linda Hamilton
Release: 2024-11-01 15:59:30
Original
222 people have browsed it

How to Extract Inner XML Content from a SimpleXMLElement Without the Wrapping Tags in PHP?

Extracting Inner XML Content with PHP SimpleXML

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

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

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

$answer_innerXML will contain the string:

Who who, <strong>who who</strong>, <em>me</em>
Copy after login

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!

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
Latest Articles by Author
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!