php xml generation with xpath

zengaddendign

New Member
I wrote a small helper function to do basic search replace using xpath, because I found it easy to write manipulations very short and at the same time easy to read and understand.Code:\[code\]<?phpfunction xml_search_replace($dom, $search_replace_rules) { if (!is_array($search_replace_rules)) { return; } $xp = new DOMXPath($dom); foreach ($search_replace_rules as $search_pattern => $replacement) { foreach ($xp->query($search_pattern) as $node) { $node->nodeValue = http://stackoverflow.com/questions/12784741/$replacement; } }}\[/code\]The problem is that now I need to do different "search/replace" on different parts of the XML dom. I had hoped something like the following would work, but DOMXPath can't use DOMDocumentFragment :(The first part (until the foreach loop) of the example below works like a charm. I'm looking for inspiration for an alternative way to go around it which is still short and readable (without to much boiler plate).Code:\[code\]<?php$dom = new DOMDocument;$dom->loadXml(file_get_contents('container.xml'));$payload = $dom->getElementsByTagName('Payload')->item(0);xml_search_replace($dom, array('//MessageReference' => 'SRV4-ID00000000001'));$payloadXmlTemplate = file_get_contents('payload_template.xml');foreach (array(array('id' => 'some_id_1'), array('id' => 'some_id_2')) as $request) { $fragment = $dom->createDocumentFragment(); $fragment->appendXML($payloadXmlTemplate); xml_search_replace($fragment, array('//PayloadElement' => $request['id'])); $payload->appendChild($fragment);}\[/code\]
 
Back
Top