DOMに関連する奇妙なバグがあります。ドキュメント内のすべてのhrefを繰り返し処理し、必要に応じて絶対パスに置き換えようとしています。問題は、を使用した後、変更された値$dom->setttribute()
をgetAttribute
返すことです。それでも、saveHTML()
getElementsByTagNameとgetAttributeを使用してタグを再度クエリすると、値はhttp://example.com/path.php?cccからhttp://example.comに切り捨てられます。
これが私のコードです:
<?php
//include 'url_to_absolute.php';
function url_to_absolute($url, $href) {
return trim($url . $href);
}
$url = 'http://example.com';
//$url = $_GET["url"];
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$contents = curl_exec($ch);
@curl_close();
$dom = new DOMDocument();
$dom->loadHTML($contents);
//change the urls to absolute
$anchors = $dom->getElementsByTagName('a');
foreach($anchors as $anchor)
{
$href = $anchor->getAttribute('href');
$abs = url_to_absolute($url, $href);
$anchor->removeAttribute('href');
$anchor->setAttribute('href', $abs);
//changed
$newhref = $anchor->getAttribute('href');
echo "newhref = " . $newhref; //shows http://example.com/.... (good)
}
$anchors = $dom->getElementsByTagName('a');
foreach($anchors as $anchor)
{
echo "new2 = " . $anchor->getAttribute('href'); //returns http://example.com only
}
//print output
echo @$dom->saveHTML();
?>