简体   繁体   中英

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM