Home  >  Article  >  Backend Development  >  How to Extract Inner XML Content from SimpleXMLElement in PHP?

How to Extract Inner XML Content from SimpleXMLElement in PHP?

DDD
DDDOriginal
2024-10-27 19:09:30647browse

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>

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>

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>

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>

Using this function:

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

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!

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