【问题标题】:PHP DOM Text ReplacePHP DOM 文本替换
【发布时间】:2017-03-13 21:29:14
【问题描述】:

我需要一些帮助来动态进行 PHP DOM 文本替换。在我的研究中,我发现了一个看起来很有前途的 PHP DOM 代码的 sn-p,但作者没有提供关于它如何工作的方法。代码链接为:http://be2.php.net/manual/en/class.domtext.php

所以,这就是我作为 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。我怎样才能让它这样做?

【问题讨论】:

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

标签: php dom xml-parsing


【解决方案1】:

这里有一个使用该功能的工作示例:

<?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>

【讨论】:

  • 我刚刚测试了代码,它按预期工作。我做错的是在domTextReplace() 中使用$doc-&gt;saveXML();。我只是看不到$doc XML 字符串会如何更新。非常感谢。
  • 我假设 XML 字符串在 DOMNode 类中得到了更新。对吗?
  • 因为函数引用了$doc(注意函数头中的 & 符号),这意味着如果您在该函数内部更改 $doc 对象,它在外部也会保持更改。请考虑验证答案:)
  • 我现在明白了。现在说得通了。
  • 就是这样!嗯,不完全是,但是是的。 “$doc DOMNode 类实例”已更新。实际上在你制作 $doc->loadXML($myXmlString); 的那一刻你可以忘记字符串,然后你总是在对象实例上工作。
猜你喜欢
  • 2011-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
  • 2020-02-06
  • 2010-12-02
  • 2018-03-25
  • 2011-06-04
相关资源
最近更新 更多