PHP简单的HTML DOM解析器>修改提取的链接

use*_*787 1 php dom

我有一个脚本,将从网站上获取内容,我想做的是修改所有链接.假设:

$html = str_get_html('<h2 class="r"><a class="l" href="http://www.example.com/2009/07/page.html" onmousedown="return curwt(this, 'http://www.example.com/2009/07/page.html')">SEO Result Boost <b> </b></a></h2>');
Run Code Online (Sandbox Code Playgroud)

那么,是否有可能以这种方式修改或重写它>

<h2 class="r"><a class="l" href="http://www.site.com?http://www.example.com/2009/07/page.html">SEO Result Boost <b> </b></a></h2>
Run Code Online (Sandbox Code Playgroud)


我已阅读它的手册,但无法理解如何计算(http://simplehtmldom.sourceforge.net/#fragment-12)

有可能,有什么想法?

Str*_*ero 5

假设相关问题答案有效,

您应该能够使用以下使用Simple HTML DOM

$site = "http://siteyourgettinglinksfrom.com";
$doc = str_get_html($code);
foreach ($doc->find('a[href]') as $a) {
$href = $a->href;
if (/* $href begins with a absolute URL path */) {
    $a->href = 'http://www.site.com?'.$href;
}
else{ /* $href begins with a relative path */        
    $a->href = 'http://www.site.com?'.$site.$href;
}

}
$code = (string) $doc;
Run Code Online (Sandbox Code Playgroud)

要么

使用PHP的本机DOM库:

$site = "http://siteyourgettinglinksfrom.com";
$doc = new DOMDocument();
$doc->loadHTML($code);
$xpath = new DOMXpath($doc);
foreach ($xpath->query('//a[@href]') as $a) {
$href = $a->getAttribute('href');
if (/* $href begins with a absolute URL path */) {
    $a->setAttribute('href', 'http://www.site.com?'.$href);
}
else{ /* $href begins with a relative path */
    $a->setAttribute('href', 'http://www.site.com?'.$site.$href);
}
}
$code = $doc->saveHTML();
Run Code Online (Sandbox Code Playgroud)

检查$ href:

您将检查相关链接并在前面提取您拉取内容的网站地址,因为大多数网站都使用相对链接.(这是正则表达式匹配器将成为您最好的朋友)

对于相对链接,您将absoute路径添加到您从中获取链接的站点

  'http://www.site.com?'.$site.$href
Run Code Online (Sandbox Code Playgroud)

对于绝对链接,您只需附加相对链接

  'http://www.site.com?'.$href
Run Code Online (Sandbox Code Playgroud)

示例链接:

网站相对: /images/picture.jpg

文件相对: ../images/picture.jpg

绝对: http://somesite.com/images/picture.jpg

(注意:这里需要做更多的工作,因为如果你处理"文档相对"链接,那么你将不得不知道你当前在哪个目录.站点相对链接应该是好的,只要你有从你获得链接的网站的根文件夹)