【问题标题】:How to replace the text of a node using DOMDocument如何使用 DOMDocument 替换节点的文本
【发布时间】:2011-08-25 12:10:15
【问题描述】:

这是我将现有 XML 文件或字符串加载到 DOMDocument 对象中的代码:

$doc = new DOMDocument();
$doc->formatOutput = true;

// the content actually comes from an external file
$doc->loadXML('<rss version="2.0">
<channel>
    <title></title>
    <description></description>
    <link></link>
</channel>
</rss>');

$doc->getElementsByTagName("title")->item(0)->appendChild($doc->createTextNode($titleText));
$doc->getElementsByTagName("description")->item(0)->appendChild($doc->createTextNode($descriptionText));
$doc->getElementsByTagName("link")->item(0)->appendChild($doc->createTextNode($linkText));

我需要覆盖标题、描述和链接标签中的值。上面代码中的最后三行是我这样做的尝试;但似乎如果节点不为空,则文本将“附加”到现有内容。如何清空节点的文本内容并在一行中追加新文本。

【问题讨论】:

    标签: php xml rss domdocument nodes


    【解决方案1】:

    改为设置DOMNode::$nodeValue

    $doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;
    $doc->getElementsByTagName("description")->item(0)->nodeValue = $descriptionText;
    $doc->getElementsByTagName("link")->item(0)->nodeValue = $linkText;
    

    这会用新值覆盖现有内容。

    【讨论】:

    • 但是如果这些字符串中存在非 xml 安全字符,这不会失败吗?我认为这就是 OP 使用 createTextNode() 的原因。
    【解决方案2】:

    正如 doub1ejack 提到的

    $doc->getElementsByTagName("title")->item(0)->nodeValue = $titleText;
    

    如果$titleText = "&amp; is not allowed in Node::nodeValue";会报错

    所以更好的解决方案是

    // clear the existing text content
    $doc->getElementsByTagName("title")->item(0)->nodeValue = "";
    
    // then create new TextNode
    $doc->getElementsByTagName("title")->item(0)->appendChild($doc->createTextNode($titleText));
    

    【讨论】:

    • 这会清除一个旧节点并添加另一个节点,留下两个节点。最好创建新节点并用它来替换旧节点
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2018-03-25
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多