PHP筛选XML xpath并导出图像
问题描述:
我有一个xml导出需要在导入之前进行筛选。PHP筛选XML xpath并导出图像
所以我写了代码来加载,过滤和保存它。
$xml = simplexml_load_file('test.xml');
$nodes = $xml->xpath('/nodes/node[ ... condition ... ]');
$nodes->asXML('filtred.xml');
但我看到asXML()
是SimpleXMLElement::function
那就是SimpleXMLElement
元素的对象。
如何将$nodes
中的所有SimpleXMLElement
元素分组使用asXML()
就可以了?
原始XML结构为:
<nodes>
<node>
<Titolo>Acquisti</Titolo>
<Corpo></Corpo>
<Nid>450</Nid>
</node>
...
</nodes>
答
基于SimpleXML: append one tree to another,你的结果是一个节点列表中的那些必须由根元素上,您可以拨打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');
我来包梁've found this http://stackoverflow.com/questions/3418019/simplexml-append-one-tree-to-another – cske
我告诉过你的问题是$ nodes是一个数组而不是SimpleXMLElement元素..所以我canìt使用SimpleXMLElement :: function,如'importNode'或'appendChild' – Shyghar