Search code examples
phpxmlxpathsimplexml

PHP filter XML xpath and export image


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>

Solution

  • 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');