0

I have XML file like:

<?xml version="1.0" encoding="UTF-8"?>
<INFO version="2.0">
  <Ad id="602867">
    <Wrapper>
      <AdSystem><![CDATA[Acudeo Compatibl]]e</AdSystem>
      <INFOTagURI>
         <![CDATA[url]]>
      </INFOTagURI>
      <Impression><![CDATA[old_url]]></Impression>
    </Wrapper>
  </Ad>
</INFO>

I want to change old_url CDATA value to new_url

I tried code like this:

$domDocument = new \DOMDocument('1.0', 'UTF-8');
$domDocument->loadXML($xml);
$impressionNode = $domDocument->getElementsByTagName("Wrapper")->item(0)->getElementsByTagName('Impression')->item(0);
$parentNode = $impressionNode->parentNode;
$oldNode = $impressionNode;
$newNode = $parentNode->appendChild($domDocument->createElement('Impression'));
$cdata = $domDocument->createCDATASection('new_url');
$newNode->appendChild($cdata);
$parentNode->removeChild($oldNode);
$parentNode->appendChild($newNode);
echo $domDocument->saveXML();

And it still returning old_url but debugging this logic I can see that $parentNode value changing to new_url, so looks like it require some logic to update parent of the parent and so to the root element??

FYI: Also, I tried to use replaceChild.

Please help me to solve this problem, thank you!

Bogdan Dubyk
  • 4,756
  • 7
  • 30
  • 67
  • What is the value of $node? It's not in your code. – LMC Jan 22 '18 at 23:27
  • sorry, it's a typo, already update it – Bogdan Dubyk Jan 23 '18 at 00:05
  • 1
    Set parent node to $parentNode = $domDocument->getElementsByTagName("Wrapper")->item(0) and then $oldNode = $parentNode->getElementsByTagName('Impression')->item(0). – LMC Jan 23 '18 at 00:22
  • 1
    this answer could help you also https://stackoverflow.com/questions/42354598/modify-cdata-in-php-xml – LMC Jan 23 '18 at 00:23

0 Answers0