2016-10-31 99 views
2

我需要一些帮助来动态地进行PHP DOM文本替换。在我的研究中,我发现PHP DOM代码片段看起来很有希望,但作者没有提供如何工作的方法。该代码的链接是:http://be2.php.net/manual/en/class.domtext.phpPHP DOM文本替换

因此,这是我在处理代码时作为DOM的新手。

$doc = new DOMDocument(); 
    $doc->preserveWhiteSpace = false; 
    $doc->loadXML($myXmlString); 

    $search = 'FirstName lastname'; 
    $replace = 'Jack Daniels';  

    $newTxt = domTextReplace($search, $replace, DOMNode &$doc, $isRegEx = false); 
    Print_r($newTxt); 

我想domTextReplace()返回$ newTxt。我怎样才能做到这一点?

+0

你不能。它内置于PHP中,但由于这只是常规DOM的扩展,所以您可以在“新”版本中查询该dom树。 –

回答

0

这里有一个工作示例使用该函数:

<?php 

$myXmlString = '<root><name>FirstName lastname</name></root>'; 

$doc = new DOMDocument(); 
$doc->preserveWhiteSpace = false; 
$doc->loadXML($myXmlString); 

$search = 'FirstName lastname'; 
$replace = 'Jack Daniels'; 

// The function doesn't return any value 
domTextReplace($search, $replace, $doc, $isRegEx = false); 

// Now the text is replaced in $doc 

$xmlOutput = $doc->saveXML(); 

// I put xml header to display the results correctly on the browser 
header("Content-type: text/xml"); 
print_r($xmlOutput); 

// I copied here the function for everyone to find it quick 
function domTextReplace($search, $replace, DOMNode &$domNode, $isRegEx = false) { 
    if ($domNode->hasChildNodes()) { 
    $children = array(); 
    // since looping through a DOM being modified is a bad idea we prepare an array: 
    foreach ($domNode->childNodes as $child) { 
     $children[] = $child; 
    } 
    foreach ($children as $child) { 
     if ($child->nodeType === XML_TEXT_NODE) { 
     $oldText = $child->wholeText; 
     if ($isRegEx) { 
      $newText = preg_replace($search, $replace, $oldText); 
     } else { 
      $newText = str_replace($search, $replace, $oldText); 
     } 
     $newTextNode = $domNode->ownerDocument->createTextNode($newText); 
     $domNode->replaceChild($newTextNode, $child); 
     } else { 
     domTextReplace($search, $replace, $child, $isRegEx); 
     } 
    } 
    } 
} 

这是输出:

<root> 
    <name>Jack Daniels</name> 
</root> 
+0

我刚刚测试了代码,它按预期工作。我在做错的是在'domTextReplace()'内使用'$ doc-> saveXML();'。我只是看不到'$ doc' XML字符串是如何得到更新的。非常感谢。 –

+0

我假设XML字符串在DOMNode类中得到了更新。那是对的吗? –

+1

由于该函数通过引用(注意函数头部中的&符号)引用'$ doc',这意味着如果您在该函数内更改$ doc对象,它将保持外部更改。 请考虑验证答案:) – nanocv