How to Fetch Inner XML with PHP SimpleXML?

Linda Hamilton
Release: 2024-10-28 03:01:02
Original
698 people have browsed it

How to Fetch Inner XML with PHP SimpleXML?

Fetching Inner XML with PHP SimpleXML

When working with XML data, extracting specific parts can be crucial. One common task is obtaining the inner HTML of an element, excluding the element's tags. This article explores how to accomplish this using PHP SimpleXML.

Problem Context

Consider 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

Our goal is to retrieve the inner HTML of the "answer" element, which is:

<code class="html">Who who, <strong>who who</strong>, <em>me</em></code>
Copy after login

Solution Using innerXML Function

PHP does not provide a built-in method to access the inner XML of an element. However, custom functions can be created to fulfill this need. One such function, SimpleXMLElement_innerXML, is defined 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

This function leverages the PHP DOM extension to convert our SimpleXMLElement ($xml) into a DOMNode object. It then iterates over its child nodes, saving each node's XML representation into the $innerXML string. Finally, $innerXML holds the element's inner HTML.

Sample Usage

To use the SimpleXMLElement_innerXML function, we can write:

<code class="php">$xml = simplexml_load_string('<qa><answer>Who who, <strong>who who</strong>, <em>me</em></answer></qa>');
$innerXML = SimpleXMLElement_innerXML($xml->answer);
echo $innerXML; // Outputs: Who who, <strong>who who</strong>, <em>me</em></code>
Copy after login

Conclusion

With the SimpleXMLElement_innerXML function, retrieving the inner XML of an element becomes straightforward. By leveraging the DOM extension, we gain precise control over XML manipulation.

The above is the detailed content of How to Fetch Inner XML with PHP SimpleXML?. 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!