php – file_get_contents( – 修复相对网址
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – file_get_contents( – 修复相对网址,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2450字,纯文字阅读大概需要4分钟。
内容图文
![php – file_get_contents( – 修复相对网址](/upload/InfoBanner/zyjiaocheng/759/5a96153f079b4e0d82a12079c688ae8b.jpg)
我试图向用户显示一个网站,使用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等)而不是正则表达式.我想你会发现它是一个更稳定的解决方案.
内容总结
以上是互联网集市为您收集整理的php – file_get_contents( – 修复相对网址全部内容,希望文章能够帮你解决php – file_get_contents( – 修复相对网址所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。