将所有链接转换为绝对URL的PHP方法

5
我正在用php编写一个网站爬虫,我已经有代码可以从网站中提取所有链接。问题是:网站使用绝对和相对url的组合。
示例(http被替换为hxxp,因为我不能发布超链接):
hxxp://site.com/
site.com
site.com/index.php hxxp://site.com/hello/index.php /hello/index.php hxxp://site2.com/index.php site2.com/index.php 我无法控制链接(它们是绝对/相对的),但我确实需要跟随它们。我需要将所有这些链接转换为绝对URL。我该如何在php中做到这一点?

2
你用什么来解析HTML并查找链接?你的库可能已经有一种方法来解决相对URL。 - Joel L
我正在使用自己编写的HTML链接提取函数。除了curl和PHP函数之外,我没有使用任何库。 - David Zorokon
1个回答

5

以下是一些入门内容:

// Your crawler was sent to this page.
$url = 'http://example.com/page';

// Example of a relative link of the page above.
$relative = '/hello/index.php';

// Parse the URL the crawler was sent to.
$url = parse_url($url);

if(FALSE === filter_var($relative, FILTER_VALIDATE_URL))
{
    // If the link isn't a valid URL then assume it's relative and
    // construct an absolute URL.
    print $url['scheme'].'://'.$url['host'].'/'.ltrim($relative, '/');
}

建议尝试使用http_build_url方法来创建绝对锚点,这是另一种方式。


1
一个相对路径也可以是 $relative = '../hello/index.php'; - Francesco

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接