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


PHP Simple HTML DOM Parser > Modify Fetched Links

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

$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>');

那么,有可能用这种方式修改或重写它吗>

<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>


我读过它的手册,但不明白如何计算它(http://simplehtmldom.sourceforge.net/#fragment-12)

有可能吗,有什么想法吗

假设相关问题的答案有效,

您应该能够使用以下方法处理SimpleHTMLDOM

$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;

使用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();

检查$href:

你会检查一个相对链接,并在提取内容的网站地址前写上,因为大多数网站都使用相对链接。(这就是正则表达式匹配器是你最好的朋友的地方)

对于相对链接,你准备了从获得链接的网站的绝对路径

  'http://www.site.com?'.$site.$href

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

  'http://www.site.com?'.$href

示例链接:

站点相对:/images/picture.jpg

文档相关:../images/picture.jpg

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

注意:这里需要做更多的工作,因为如果你处理"文档相关"链接,那么你必须知道你当前所在的目录。站点相关链接应该很好,只要你有从中获取链接的站点的根文件夹)