How to Extract Inner XML Content from SimpleXMLElement in PHP?

DDD
Release: 2024-10-27 19:09:30
Original
646 people have browsed it

How to Extract Inner XML Content from SimpleXMLElement in PHP?

PHP SimpleXML: Accessing Inner XML

In XML manipulation with PHP's SimpleXML, it is often necessary to retrieve the inner HTML content of an element without the enclosing tag. This article explores how to achieve this using SimpleXML.

Consider the following XML structure:

<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 content of the "answer" element as a string, the following methods are available:

Using asXML():

<code class="php">$answer = new SimpleXMLElement($xml);
$innerXML = $answer->asXML(); // Returns "<answer>Who who, <strong>who who</strong>, <em>me</em></answer>"</code>
Copy after login

Using DOMDocument:

<code class="php">$answer = new SimpleXMLElement($xml);
$dom = dom_import_simplexml($answer);
$innerXML = $dom->ownerDocument->saveXML($dom); // Returns "Who who, <strong>who who</strong>, <em>me</em>"</code>
Copy after login

Using a Custom Function:

The following custom function can be defined to extract inner XML:

<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

Using this function:

<code class="php">$innerXML = SimpleXMLElement_innerXML($answer); // Returns "Who who, <strong>who who</strong>, <em>me</em>"</code>
Copy after login

These methods provide options to extract the inner XML of SimpleXML elements, enabling efficient manipulation and retrieval of XML content.

The above is the detailed content of How to Extract Inner XML Content from 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!