PHP使用xpath对网页内容批量替换


$string = "<html> ..... ";
$replacementHTML = "<a href=''>欢迎光临</a>";
$xpath = '/html/body/div[2]/div/div[1]/p[2]';

xpathHandle($string,$xpath,$replacementHTML);

function xpathHandle(&$sourceHTML,$xpath,$replacementHTML){
    $dom = new DOMDocument;
    @$dom->loadHTML($sourceHTML);
    $replacement = $dom->createDocumentFragment();
    $replacement->appendXML($replacementHTML);
    $domXpath = new DOMXPath($dom);
    $oldNode = $domXpath->query($xpath)->item(0);

    $childLength = $oldNode->childNodes->length;
    for ($i = 0; $i < $childLength; $i++) {
        $oldNode->removeChild($oldNode->childNodes->item(0));
    }

     $oldNode->appendChild($replacement);
     $sourceHTML = $dom->saveXml($dom->documentElement);
}


echo $string;
exit();
posted @ 2022-04-24 08:58  jasondayee  阅读(222)  评论(0编辑  收藏  举报