1

How can i get the content of an XML as string? I have a xml like this:

<?xml version="1.0" encoding="utf-8"?>
<section>
  <paragraph>some content</paragraph>
  <custom>some more content</custom>
</section>

and i want the content of section as a string like this:

  <paragraph>some content</paragraph>
  <custom>some more content</custom>

every doc i read so far only explains how to get the content of a subnode but not of the root node.

Camel
  • 15
  • 2

2 Answers2

0

You can use xml parser for create an array and work with it. For example:

<?php
$xml = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<section>
  <paragraph>some content</paragraph>
  <custom>some more content</custom>
</section>
XML;

$values = [];
$p = xml_parser_create();
xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($p, $xml, $values);
xml_parser_free($p);

var_dump($values);

http://php.net/manual/en/ref.xml.php

buildok
  • 785
  • 6
  • 7
0

It can be achieved using DOMDocument (Press here to See it in action)

$xmlStr = '<?xml version="1.0" encoding="utf-8"?>
<section>
  <paragraph>some content</paragraph>
  <custom>some more content</custom>
</section>
';

$xml = new DOMDocument(); 
$xml->loadXML($xmlStr);
if($xml->childNodes->length > 0) {
  foreach($xml->childNodes->item(0)->childNodes as $rootChildNode){
      echo $xml->saveXML($rootChildNode); 
    }
}
Dorad
  • 3,413
  • 2
  • 44
  • 71
  • ok i have to iterate trough childnodes, i hoped there is some method to fetch the content at once. thx – Camel Jul 07 '17 at 08:28
  • Hi camel. Thanks for accepting my answer. I think there is no such a way without iteration. Look at https://stackoverflow.com/questions/2087103/how-to-get-innerhtml-of-domnode – Dorad Jul 07 '17 at 09:41