Web ページ上のすべての href リンクを見つけて、リンクを独自のプロキシ リンクに置き換えようとしています。
例えば
<a href="http://www.google.com">Google</a>
する必要がある
<a href="http://www.example.com/?loadpage=http://www.google.com">Google</a>
Web ページ上のすべての 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 ( docsloadHTMLFile
) を使用して HTML を取得するか、次のメソッドを使用できます。DomDocument
ドキュメンテーション
DomDocument
- http://php.net/manual/en/class.domdocument.phpDomElement
- http://www.php.net/manual/en/class.domelement.phpDomElement::getAttribute
- http://www.php.net/manual/en/domelement.getattribute.phpDOMElement::setAttribute
- http://www.php.net/manual/en/domelement.setattribute.phpurlencode
- http://php.net/manual/en/function.urlencode.phpDomDocument::loadHTMLFile
- http://www.php.net/manual/en/domdocument.loadhtmlfile.phpリンクをjQueryに置き換えたい場合の別のオプションは、次のこともできます。
$(document).find('a').each(function(key, element){
curValue = element.attr('href');
element.attr('href', 'http://www.example.com?loadpage='+curValue);
});
ただし、より安全な方法は、php オフコースで行うことです。
これを行うために私が考えることができる最も簡単な方法:
$loader = "http://www.example.com?loadpage=";
$page_contents = str_ireplace(array('href="', "href='"), array('href="'.$loader, "href='".$loader), $page_contents);
しかし、それは ? を含む URL に問題があるかもしれません。また &。または、ドキュメントのテキスト (コードではない) に href=" が含まれている場合