DOM과 관련된 이상한 버그가 있습니다. 문서 안의 모든 href를 반복하고 필요하다면 절대 경로로 대체하려고합니다. 문제는 $dom->setttribute()
을 사용한 후 변경된 값을 getAttribute
이 반환한다는 것입니다. 그러나 saveHTML()
또는 getElementsByTagName 및 getAttribute를 사용하여 태그를 다시 쿼리하는 경우 값은 http://example.com/path.php?ccc에서 http://example.com까지 잘 렸습니다.PHP에서 DOM으로 속성을 변경하면 올바르게 저장되지 않습니다.
<?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();
?>
당신이 당신의 url_to_absolute() 함수를 게시하시기 바랍니다 수를 ? 그리고 스 니펫에서 $ url 변수가 존재하지 않습니다. – pp19dd
내 url_to_absolute 기능 : http://nadeausoftware.com/articles/2008/05/php_tip_how_convert_relative_url_absolute_url#Code –
my $ url 변수가 $ url = $ _GET [ 'url']으로 미리 설정되었습니다. –