Php 如何在不删除其子节点的情况下更改节点的textValue
想象一下这个HTML:Php 如何在不删除其子节点的情况下更改节点的textValue,php,dom,Php,Dom,想象一下这个HTML: <html> <head><title>Nice page</title></head> <body>Hello World <a href=http://google.com>This is a link</a> <br /> <a href=http://www.google.com&
<html>
<head><title>Nice page</title></head>
<body>Hello World <a href=http://google.com>This is a link</a>
<br />
<a href=http://www.google.com> this also
<img src=wrong.image> and here
</a>
</body>
</html>
如何保存子节点?您可以使用xpath查询专门获取链接中的文本节点
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("example.html");
$xpath = new DOMXPath($doc);
$linkTextNodes = $xpath->query('//a/descendant::text()');
foreach ($linkTextNodes as $node) {
$node->textContent = strtoupper($node->textContent);
}
echo $doc->saveHTML();
可以使用xpath查询专门获取链接中的文本节点
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("example.html");
$xpath = new DOMXPath($doc);
$linkTextNodes = $xpath->query('//a/descendant::text()');
foreach ($linkTextNodes as $node) {
$node->textContent = strtoupper($node->textContent);
}
echo $doc->saveHTML();
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("example.html");
$xpath = new DOMXPath($doc);
$linkTextNodes = $xpath->query('//a/descendant::text()');
foreach ($linkTextNodes as $node) {
$node->textContent = strtoupper($node->textContent);
}
echo $doc->saveHTML();