Suppose I have a XML file with a structure unknown to me. But I know that somewhere in that xml structure, one node has a known value, for instance, {1} as in node->nodeValue="{1}".
How can I create another XML file, identical to the first one, but with that value {1} replaced with another value (‘New value’)?
Here’s what I’ve tried, without sucess:
$xmlfile=$this->xmlPath.'document1.xml';
$xmlwfile=$this->xmlPath.'document2.xml';
$this->xml = new XMLReader();
$this->xml->open($xmlfile);
$this->wxml = new DOMDocument();
while($this->xml->read())
{
$node = $this->xml->expand();
if($this->xml->nodeType == XMLReader::TEXT)
{
if(str_contains($this->xml->value,"{1}"))
{
$node->nodeValue='New Value';
}
}
$this->wxml->appendChild($this->wxml->importNode($node, true));
}
$this->wxml->save($xmlwfile);
$this->xml->close();
Any thoughts?
Thanks,
Pedro
2
Answers
Here is XSLT based solution that is using a so called Identity Transform pattern.
You just need to launch XSLT transformation in php.
Input XML
XSLT
Output XML
XMLReader/XMLWriter are used for large XMLs. For "normal" documents, DOM is easier because it loads the whole document and allows you to use Xpath expressions to fetch nodes.
Output: