如何从锚点href获取完全限定的URL


How to get fully-qualified URL from anchor href?

我正在用php编写一个网络爬虫。给定一个当前URL,以及指向绝对URL、相对URL和根URL的链接数组,我将如何确定每个链接的完全限定URL?

例如,我假设我正在爬网URL:

http://www.example.com/path/to/my/file.html

网页包含的链接数组是:

array(
    'http://www.some-other-domain.com/',
    '../../',
    '/search',
);

如何确定每个链接的完全限定URL?我在这个例子中寻找的结果将分别是:

http://www.some-other-domain.com/
http://www.example.com/path/
http://www.example.com/search/

我认为最简单的方法是使用这样的库:http://www.electrictoolbox.com/php-resolve-relative-urls-absolute/

链接示例:

url_to_absolute('http://www.example.com/sitemap.html', 'aboutus.html');

解析为http://www.example.com/aboutus.html

url_to_absolute('http://www.example.com/content/sitemap.html', '../images/somephoto.jpg');

解析为http://www.example.com/images/somephoto.jpg