在DOM中查找最后一个文本节点 [英] Find last text node in DOM

查看:94
本文介绍了在DOM中查找最后一个文本节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些html字符串:

I have some html string:

$ string-来自用户的字符串。

$string - a string taken from user.

$dom = new DomDocument;
$dom ->preserveWhiteSpace = false;
$dom ->loadHTML('<?xml encoding="UTF-8">'.$string);

如何使用PHP在DOM树中找到最后一个文本节点?我想做的是在找到的字符串的末尾添加一些额外的字符。接下来,我将旧文本节点替换为新字符串。

How can I find a last text node in DOM tree using PHP? What I want to do is to add some extra chars at the end of to finded string. Next I'll replace old text node with the new string.

推荐答案

假设

$xml = <<< XML
<a>
    First Text Node
    <b>foo</b>
    Another Text Node
    <c>bar</c>
    Not the last Text Node
    <empty/>
</a>
XML;

使用此代码:

$dom = new DOMDocument;
$dom->loadXml($xml);
$xp = new DOMXPath($dom);
$textNodes = $xp->query('//text()');
$lastTextNode = $textNodes->item($textNodes->length - 1);
$lastTextNode->nodeValue .= 'some stuff appended to the end';
echo $dom->saveXml();

将输出:

<?xml version="1.0"?>
<a>
    First Text Node
    <b>foo</b>
    Another Text Node
    <c>bar</c>
    Not the last Text Node
    <empty/>
some stuff appended to the end</a>

如果这不是您认为的最后一个节点,请说明问题。

If this is not what you consider the last node, please clarify the question.

这篇关于在DOM中查找最后一个文本节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆