更改特定DOM节点PHP

时间:2015-04-16 01:59:17

标签: php dom

我有以下代码:

$item = "What I have: <a href='/id/blablabla'>This $oldtext.</a>";
$dom = new DOMDocument;
$dom->loadHTML($item);
foreach ($dom->getElementsByTagName('a') as $node) {
    if(strpos($node->getAttribute('href'),'/id/') !== false) {
         $oldtext = // ?
         $newtext = "This is old:".$oldtext."And this is new: New.";
         // then replace 'This $oldtext.' in $item as $newtext
    }
}

检查$item中的任何节点是否包含/ id /的href。如果他们这样做,他们应该保存节点的当前文本(称为$oldtext ),然后用新文本替换文本,将使用新文本中$oldtext

编辑:为了清晰起见,我添加了$ item的内容。

即使节点发生变化,如何保存$oldtext并更改节点本身?

2 个答案:

答案 0 :(得分:0)

我认为您需要做的就是使用$node->setAttribute('href', $newtext);替换文本,然后通过执行以下操作保存HTML:$dom->saveHTML();

请参阅下面的完整示例:

    $item = "What I have: <a href='/id/blablabla'>This $oldtext.</a>";
    $dom = new DOMDocument;
    $dom->loadHTML($item);
    foreach ($dom->getElementsByTagName('a') as $node) {
        if(strpos($node->getAttribute('href'),'/id/') !== false) {
             $oldtext = // ?
             $newtext = "This is old:".$oldtext."And this is new: New.";
             // then replace 'This $oldtext.' in $item as $newtext
            $node->setAttribute('href', $newtext);
        }
    }

   $dom->saveHTML();

答案 1 :(得分:0)

如果您指的是文本节点,那么只需访问->nodeValue属性即可。只需像任何可访问的对象属性一样覆盖它:

$item = "What I have: <a href='/id/blablabla'>This \$oldtext.</a>";
$dom = new DOMDocument;
$dom->loadHTML($item);
foreach ($dom->getElementsByTagName('a') as $node) {
    if(strpos($node->getAttribute('href'),'/id/') !== false) {
         $oldtext = $node->nodeValue;
         $node->nodeValue = "This is old:".$oldtext."And this is new: New.";
         // then replace 'This $oldtext.' in $item as $newtext
    }
}
echo $dom->saveHTML();

Sample Output