Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/244.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以用php在所有xml节点中使用str_replace吗?_Php_Xml_Str Replace_Xmlnode - Fatal编程技术网

我可以用php在所有xml节点中使用str_replace吗?

我可以用php在所有xml节点中使用str_replace吗?,php,xml,str-replace,xmlnode,Php,Xml,Str Replace,Xmlnode,我认为问题在于我的逻辑,我可能走错了方向。我想要的是 使用php打开xml文档 按标记名获取元素 然后对于具有子节点的每个节点 将每个字母a替换为ა每个b带ბ等等 这是我的代码,但它不工作 xmlDoc=loadXMLDoc("temp/word/document.xml"); $nodes = xmlDoc.getElementsByTagName("w:t"); foreach ($nodes as $node) { while( $no

我认为问题在于我的逻辑,我可能走错了方向。我想要的是

  • 使用php打开xml文档
  • 按标记名获取元素
  • 然后对于具有子节点的每个节点
  • 将每个字母
    a
    替换为
    每个
    b
    等等
这是我的代码,但它不工作

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.
    }

我想这可能是因为有多个
str_replace()
调用,但即使只有一个调用也不起作用。我这样做是错误的还是遗漏了什么?

每次迭代都会覆盖
$node
变量,因此只有最后一个
$node
会被修改(如果有)。您需要在循环内进行替换,然后使用
saveXML()
方法返回修改后的XML标记

您的代码(有一些改进):


啊,这看起来不错,所以这仍然适用于每个w:t替换tag@gcoulby:是;你为什么不试试看呢?我不得不离开家。我会在一小时后回来,我会告诉你最新情况。如果我用“code”$xmlContents=file\u get\u contents($word\u dir);取消链接($word_dir);文件内容($word\u dir,$xmlContents);'这个方法的问题是它改变了XML文件中的每个字符,有效地破坏了文件。。。因此需要节点。但是,您的代码不能使用此方法。该程序通过概念,甚至覆盖了文件,但所有的字母都保持不变
$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();