Home  >  Article  >  Backend Development  >  How to Extract Inner XML Content from a SimpleXMLElement Without the Wrapping Tags in PHP?

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

Linda Hamilton
Linda HamiltonOriginal
2024-11-01 15:59:30223browse

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>

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>

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>

$answer_innerXML will contain the string:

Who who, <strong>who who</strong>, <em>me</em>

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!

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