【问题标题】:file_get_contents does not work with MAMPfile_get_contents 不适用于 MAMP
【发布时间】:2014-08-03 21:36:36
【问题描述】:

我在 MAMP 中创建了一个 index.php 页面。

我的 index.php 与以下内容完全相同。我通过 localhost:8888 访问它。

<?php

echo file_get_contents("http://stackoverflow.com");

?>

但是,它并没有像我相信的那样从该页面返回 html 源代码,而是将 http://stackoverflow.com 作为常规网页返回,就像您现在正在查看的网页一样。

我的 MAMP 使用的是 PHP 5.5.10。 user_agent 已设置并且 allow_url_fopen 已打开。

我很困惑。我将非常感谢任何解释:)

【问题讨论】:

  • 你对带有 URL 的 file_get_contents() 的期望是错误的:你没有得到源代码,你得到了标记;如果您将其回显到浏览器,它将显示该 pge.... 这就是互联网的工作方式
  • var_dump(file_get_contents("http://stackoverflow.com"));您的浏览器正在渲染html!!
  • “作为常规网页”是什么意思?该代码返回 stackoverflow.com 的 HTML
  • 它正在返回源代码,但是当您通过网络浏览器查看它时,它会被解释。

标签: php mamp file-get-contents


【解决方案1】:

它正在返回 html,浏览器正在解释它。

您可以尝试将输出包装在 标签中:

<?php

echo '<code>' . file_get_contents("http://stackoverflow.com") . '</code>';

?>

或者将标题设置为 text/plain 而不是 html:

<?php

header('Content-Type: text/plain');
echo file_get_contents("http://stackoverflow.com");

?>

或者,如果您想保留标头而不将输出注入代码标签:

<?php

echo htmlspecialchars(file_get_contents("http://stackoverflow.com"));

?>

我更喜欢最后一个。

【讨论】:

  • 非常感谢。感谢您抽出宝贵时间回答:)
【解决方案2】:

如果你想看到纯文本,你可以使用以下,

<?php 
header('Content-Type:text/plain');
echo file_get_contents("http://stackoverflow.com");
?>

您在版本中看到的内容是正确的,因为 HTML 是由您的 Internet 浏览器呈现的。

【讨论】:

  • 非常感谢您的回答:)
【解决方案3】:

php 脚本的结果默认发送到 bowser,所以你的代码

<?php
   echo file_get_contents("http://stackoverflow.com");
?>

正在阅读网页,然后将其发送到您的浏览器。所以看起来它只是显示您阅读的页面。

如果你改成

<?php
    $page = file_get_contents("http://stackoverflow.com");
?>

然后你可以对存储在$page中的网页源做一些事情。

【讨论】:

  • 非常感谢您的回答:)
猜你喜欢
  • 2011-06-22
  • 1970-01-01
  • 2012-02-10
  • 2018-01-06
  • 1970-01-01
  • 1970-01-01
  • 2016-07-19
  • 1970-01-01
  • 2013-06-26
相关资源
最近更新 更多