1

I have a xml export that needs to be filtered before it can be imported.

So I wrote code to load, filter and save it.

$xml = simplexml_load_file('test.xml');
$nodes = $xml->xpath('/nodes/node[ ... condition ... ]'); 

$nodes->asXML('filtred.xml');

But I saw that asXML() is a SimpleXMLElement::function and that is an object of SimpleXMLElement elements.

How can I group all the $nodes in a general SimpleXMLElement element to use asXML() on it?

The original XML structure is:

<nodes>
  <node>
    <Titolo>Acquisti</Titolo>
    <Corpo></Corpo>
    <Nid>450</Nid>
  </node>

  ...

</nodes>
Robin Mackenzie
  • 18,801
  • 7
  • 38
  • 56
Shyghar
  • 313
  • 4
  • 19
  • I've found this http://stackoverflow.com/questions/3418019/simplexml-append-one-tree-to-another – cske Nov 11 '16 at 17:17
  • I told you the problem is that $nodes is an array and not a SimpleXMLElement element.. so I canìt use SimpleXMLElement::function like 'importNode' or 'appendChild' – Shyghar Nov 14 '16 at 10:53

1 Answers1

0

Based on SimpleXML: append one tree to another, your result is a list of nodes those have to be wraped by a root element on which you can call asXml

$xmlIn = '
<nodes>
  <node>
    <Titolo>Acquisti</Titolo>
    <Corpo></Corpo>
    <Nid>450</Nid>
  </node>
  <node>
    <Titolo>Acquisti 2</Titolo>
    <Corpo></Corpo>
    <Nid>450</Nid>
  </node>
  <node>
    <Titolo>Acquisti 2</Titolo>
    <Corpo></Corpo>
    <Nid>450</Nid>
  </node>
</nodes>
';

$xml = simplexml_load_string($xmlIn);
$nodes = $xml->xpath('/nodes/node');

$xmlOut = new SimpleXMLElement('<nodes></nodes>');

$domOut = dom_import_simplexml($xmlOut);

foreach ($nodes as $n) {
    $tmp  = dom_import_simplexml($n);
    $tmp  = $domOut->ownerDocument->importNode($tmp, TRUE);
    $domOut->appendChild($tmp);
}

$xmlOut->asXML('filtred.xml');
Community
  • 1
  • 1
cske
  • 2,233
  • 4
  • 26
  • 24