使用file_get_contents并更改包含页面上的链接域


Using file_get_contents And Changing Domain of Links on the Included Page?

在我的页面上,我有这段代码:

<?php
$homepage = file_get_contents('http://www.nbc.com/');
echo $homepage;
?>

它完美地包含了NBC网站,但我注意到 NBC.com 网站上的所有链接都以我的域名开头,而不是 http://nbc.com 所以它们不起作用。

因此,例如,http://nbc.com/the-blacklist/episodes 不是显示在 http://nbc.com 网站上,而是显示 http://my-domain.com/the-blacklist/episodes。

有什么方法可以使用file_get_contents确实将页面包含在我的URL中,但请确保页面上的所有链接都是原始链接,以便它们正常工作?

您正在拉取的页面内部的链接使用相对链接(/page.html)而不是完整的URL,您需要对变量或字符串替换执行正则表达式。要对其进行测试,您可以执行以下操作:

$domain = 'http://www.nbc.com';
$pull = file_get_contents($domain);
echo str_replace('href="/', 'href="' . $domain . '/', $pull);