在 php 中使用 file_get_content 时如何保留缩进? [英] How can I retain indentation while using file_get_content with php?
问题描述
我在 php 中使用 file_get_contents
函数来获取站点的内容.问题是,在我从中获取信息的站点上,信息被整齐地缩进,但当我检索信息时,它会丢失所有缩进.
我使用的代码是:
如果您访问此处的原始站点,您可以看到信息是如何设置的:
<代码>{"id": "220439","name": "布雷特泰勒","first_name": "布雷特","last_name": "泰勒","link": "https://www.facebook.com/btaylor","用户名": "btaylor","性别": "男","locale": "en_US"}
在我的网站上,抓取信息后,它看起来像这样:
{"id":"220439","name":"Bret Taylor","first_name":"Bret","last_name":"Taylor","link":"http:\/\/www.facebook.com\/btaylor","username":"btaylor","gender":"male","locale":"en_US"}
如何保持缩进?
提前致谢!
顺便说一下,链接和信息来自 Facebook 的示例页面,并非真实信息.
这与 file_get_contents代码>
.它完全取决于页面的 Content-Type
.原始是纯文本,而您的网站输出 HTML.
您可以使用:
header("Content-Type: text/plain");
或者保留 HTML 类型,但将输出包装在 pre
标签中:
echo "$file
";
由于您可能想重用镜像的 JSON 输出,我会选择第一个选项.(但是 application/json
类型可能更合适.不知道你为什么要以固定格式呈现它.)
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.
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.)
这篇关于在 php 中使用 file_get_content 时如何保留缩进?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!