[英]Update links in HTML using PHP DOMDocument and DOMXPath
因此,我需要更新某些HTML中的所有圖像鏈接。 假設我的HTML如下所示:
<html>
<body>
<div class="content">
<p><a href="example-1.html">This</a> is a normal link. I don't want to change this link.</p>
<p>But this is an image link: <a href="example-1.html"><img src="http://fpoimg.com/150"></a></p>
</div>
</body>
</html>
我試圖使用PHP的DOMDocument和DOMXPath將所有圖像鏈接(即僅包含圖像的鏈接)替換為example-2.html。
這是我到目前為止的代碼:
$dom = new DOMDocument();
$dom->loadHTML( $content );
$imgs = $dom->getElementsByTagName("img");
foreach ($imgs as $img) {
$parent = $img->parentNode;
}
我不確定抓取所有圖像然后檢查父級,或抓取所有鏈接然后檢查子級是否更快。 我認為頁面上的常規文本鏈接將比圖像更多,因此我認為前者會更快。
我只是不確定從這里去哪里。
當你確實需要更新a
標簽,你應該嘗試使用導致你這些的XPath a
標簽包含一個img
標記。 使用以下XPath和代碼可以實現:
$dom = new DOMDocument();
$dom->loadHTML( $content );
$xpath = new DOMXPath( $dom );
$anchor_list = $xpath->query( "//a[img[@src]]" );
foreach($anchor_list as $a) {
$url = $a->getAttribute('href');
// modify url ...
$url = str_replace("this", "that", $url);
$a->setAttribute('href', $url);
}
$content = $dom->saveHTML( );
echo $content;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.