How can I retain indentation while using file_get_content with php?

六月ゝ 毕业季﹏ 提交于 2019-12-11 12:44:27

问题


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:


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.)



来源:https://stackoverflow.com/questions/9058409/how-can-i-retain-indentation-while-using-file-get-content-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!