$html = file_get_contents("any site");
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
echo $image->src;
}
不给我任何返回
$html = file_get_contents("any site");
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
echo $image->getAttribute('src');
}
返回相对网址,如“/images/example.jpg
$html = file_get_contents("any site");
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
echo $image.src;
}
返回给我:
Fatal error: Call to undefined function getElementsByTagName()
那么,如何获得绝对路径呢?
最佳答案
您可以使用parse_url查找基本 URL:
$url = 'http://www.example.com/path?opt=234';
$parts = parse_url($url);
if (isset($parts['scheme'])){
$base_url = $parts['scheme'].'://';
} else {
$base_url = 'http://';
$parts = parse_url($base_url.$url);
}
$base_url .= $parts['host'];
if (isset($parts['path'])){
$base_url .= $parts['path'];
}
然后将其与您的代码结合起来,如下所示:
$html = file_get_contents("any site");
$dom = new domDocument;
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
echo $base_url.$image->getAttribute('src');
}
关于php - 如何获取完整的url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17380354/