How can I retain indentation while using file_get_

2019-07-31 06:38发布

I am using the file_get_contents function in php to get the contents of a site. The problem is that on the site I am grabbing information from, the information is neatly indented, yet when I retrieve the information it looses all indentation.

The code I am using is:

<?php
$url = "https://graph.facebook.com/btaylor";
$file = file_get_contents($url);
echo "$file";
?>

If you go to the original site here, you can see how the information is set up as:

{
   "id": "220439",
   "name": "Bret Taylor",
   "first_name": "Bret",
   "last_name": "Taylor",
   "link": "https://www.facebook.com/btaylor",
   "username": "btaylor",
   "gender": "male",
   "locale": "en_US"
}

yet on my site, after grabbing the information it looks like this:

{"id":"220439","name":"Bret Taylor","first_name":"Bret","last_name":"Taylor","link":"http:\/\/www.facebook.com\/btaylor","username":"btaylor","gender":"male","locale":"en_US"}

How can I keep the indentation?

Thanks in advance!

By the way, the link and information is from a sample page from Facebook, and not real information.

1条回答
2楼-- · 2019-07-31 07:23

This has nothing to do with file_get_contents. It solely depends on the Content-Type of your page. The original is plain text, while your site outputs HTML.

You can either use:

 header("Content-Type: text/plain");

Or keep the HTML type but wrap your output in pre tags:

 echo "<pre>$file</pre>";

Since you possibly want to reuse that mirrored JSON output, I would go for the first option. (But then an application/json type might be more appropriate. Not sure why you want to present it with fixed formatting anyway.)

查看更多
登录 后发表回答