简体   繁体   中英

file_get_contents does not work with MAMP

I have created an index.php page in MAMP.

My index.php reads exactly like the following. I access it through localhost:8888.

<?php

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

?>

However, instead of returning the html source code from this page as I believe it would do, it just returns http://stackoverflow.com as a regular webpage, like the webpage you are looking at now.

My MAMP is using PHP 5.5.10. The user_agent is set and allow_url_fopen is on.

I am severely confused. I would very much appreciate any explanations :)

If you want to see the plain text you can use the following,

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

What you see in your version is correct, since the HTML is rendered by your internet browser.

It IS returning the html and the browser is interpreting it.

You can try wrap the output in tags:

<?php

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

?>

Or set headers as text/plain instead of html:

<?php

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

?>

Or if you want to keep the headers and not inject the output into code tags:

<?php

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

?>

I prefer the last one.

The results of a php script are by default sent to the bowser, so your code

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

Is reading the web page and then sending it to your browser. So it looks like it is just showing the page you read.

If you change it to

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

Then you can do something with the web page source stored in $page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM