我正在尝试查找网页上的所有href链接,并将链接替换为我自己的代理链接。
例如
<a href="http://www.google.com">Google</a>
需要
<a href="http://www.example.com/?loadpage=http://www.google.com">Google</a>
使用 PHP 的DomDocument
来解析页面
$doc = new DOMDocument();
// load the string into the DOM (this is your page's HTML), see below for more info
$doc->loadHTML('<a href="http://www.google.com">Google</a>');
//Loop through each <a> tag in the dom and change the href property
foreach($doc->getElementsByTagName('a') as $anchor) {
$link = $anchor->getAttribute('href');
$link = 'http://www.example.com/?loadpage='.urlencode($link);
$anchor->setAttribute('href', $link);
}
echo $doc->saveHTML();
在这里查看: http://codepad.org/9enqx3Rv
如果你没有 HTML 作为字符串,你可以使用 cUrl(docs)来获取 HTML,或者你可以使用 loadHTMLFile
方法来DomDocument
文档
-
DomDocument
- http://php.net/manual/en/class.domdocument.php -
DomElement
- http://www.php.net/manual/en/class.domelement.php -
DomElement::getAttribute
- http://www.php.net/manual/en/domelement.getattribute.php -
DOMElement::setAttribute
- http://www.php.net/manual/en/domelement.setattribute.php -
urlencode
- http://php.net/manual/en/function.urlencode.php -
DomDocument::loadHTMLFile
- http://www.php.net/manual/en/domdocument.loadhtmlfile.php - cURL - http://php.net/manual/en/book.curl.php
如果你想
用jQuery替换链接,你也可以执行以下操作:
$(document).find('a').each(function(key, element){
curValue = element.attr('href');
element.attr('href', 'http://www.example.com?loadpage='+curValue);
});
然而,一种更安全的方法是在 php offcourse 中执行此操作。
我能想到的最简单的方法:
$loader = "http://www.example.com?loadpage=";
$page_contents = str_ireplace(array('href="', "href='"), array('href="'.$loader, "href='".$loader), $page_contents);
但是,包含 ? 或 &. 的网址可能会有一些问题。 或者,如果文档的文本(不是代码)包含 href="