can I use str_replace in all xml nodes with php?

927 views Asked by At

I think the problem is with my logic and I am probably going about this the wrong way. What I want is to

  • open an xml document with php
  • get elements by Tag name
  • then for each node that has child nodes
  • replace every letter a with every b with and so on.

here is the code I have so for but it doesn't work.

xmlDoc=loadXMLDoc("temp/word/document.xml");
    $nodes = xmlDoc.getElementsByTagName("w:t");

        foreach ($nodes as $node) {
            while( $node->hasChildNodes() ) {
                $node = $node->childNodes->item(0);
            }
            $node->nodeValue = str_replace("a","ა",$node->nodeValue);
            $node->nodeValue = str_replace("b","ბ",$node->nodeValue);
            $node->nodeValue = str_replace("g","გ",$node->nodeValue);
            $node->nodeValue = str_replace("d","დ",$node->nodeValue);

            // More replacements for each letter in the alphabet.
    }

I thought it might be because of the multiple str_replace() calls but it doesn't work with even just one. Am I going about this the wrong way or have I missed something?

1

There are 1 answers

5
Amal Murali On

The $node variable gets overwritten on each iteration, so only the last $node will get modified (if ever). You need to do the replacement inside the loop and then use saveXML() method to return the modified XML markup.

Your code (with some improvements):

$xmlDoc = new DOMDocument();
$xmlDoc->load('temp/word/document.xml');

foreach ($xmlDoc->getElementsByTagName("w:t") as $node) {
    while($node->hasChildNodes()) {
        $node = $node->childNodes->item(0);
        $search = array('a', 'b', 'g', 'd');
        $replace = array('ა', 'ბ', 'გ', 'დ');
        $node->nodeValue = str_replace($search, $replace, $node->nodeValue);
    }
}

echo $xmlDoc->saveXML();