这里有一个工作示例使用该函数:
<?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>
你不能。它内置于PHP中,但由于这只是常规DOM的扩展,所以您可以在“新”版本中查询该dom树。 –