加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – file_get_contents( – 修复相对网址

发布时间:2020-12-13 21:58:24 所属栏目:PHP教程 来源:网络整理
导读:我试图向用户显示一个网站,使用php下载它. 这是我正在使用的脚本: ?php$url = 'https://stackoverflow.com/pagecalledjohn.php';//Download page$site = file_get_contents($url);//Fix relative URLs$site = str_replace('src="','src="' . $url,$site);$s
我试图向用户显示一个网站,使用php下载它.
这是我正在使用的脚本:

<?php
$url = 'https://stackoverflow.com/pagecalledjohn.php';
//Download page
$site = file_get_contents($url);
//Fix relative URLs
$site = str_replace('src="','src="' . $url,$site);
$site = str_replace('url(','url(' . $url,$site);
//Display to user
echo $site;
?>

到目前为止,除了str_replace函数的一些主要问题之外,这个脚本还可以处理.问题来自相对网址.如果我们在我们制作的一张猫的pagecalledjohn.php上使用一个图像(像这样:).这是一个png,我认为它可以使用6个不同的URL放在页面上:

1. src="//www.stackoverflow.com/cat.png"
2. src="http://www.stackoverflow.com/cat.png"
3. src="https://www.stackoverflow.com/cat.png"
4. src="somedirectory/cat.png"

4在这种情况下不适用但无论如何都要添加!

5. src="/cat.png"
6. src="cat.png"

有没有办法,使用php,我可以搜索src =“并将其替换为正在下载的页面的url(文件名已删除),但如果是选项1,2或3并且稍微更改程序,则不会在其中粘贴url 4,5和6?

解决方法

而不是尝试更改源代码中的每个路径引用,为什么不简单地注入< base>标题中的标记是否明确指出应在何时计算所有相对URL的基本URL?

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base

这可以使用您选择的DOM操作工具来实现.下面的示例将演示如何使用DOMDocument和相关类来执行此操作.

$target_domain = 'https://stackoverflow.com/';
$url = $target_domain . 'pagecalledjohn.php';
//Download page
$site = file_get_contents($url);
$dom = DOMDocument::loadHTML($site);

if($dom instanceof DOMDocument === false) {
    // something went wrong in loading HTML to DOM Document
    // provide error messaging and exit
}

// find <head> tag
$head_tag_list = $dom->getElementsByTagName('head');
// there should only be one <head> tag
if($head_tag_list->length !== 1) {
    throw new Exception('Wow! The HTML is malformed without single head tag.');
}
$head_tag = $head_tag_list->item(0);

// find first child of head tag to later use in insertion
$head_has_children = $head_tag->hasChildNodes();
if($head_has_children) {
    $head_tag_first_child = $head_tag->firstChild;
}

// create new <base> tag
$base_element = $dom->createElement('base');
$base_element->setAttribute('href',$target_domain);

// insert new base tag as first child to head tag
if($head_has_children) {
    $base_node = $head_tag->insertBefore($base_element,$head_tag_first_child);
} else {
    $base_node = $head_tag->appendChild($base_element);
}

echo $dom->saveHTML();

至少,你真的想要修改源代码中的所有路径引用,我强烈建议使用DOM操作工具(DOMDOcument,DOMXPath等)而不是正则表达式.我想你会发现它是一个更稳定的解决方案.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读