在PHP中使用file_get_content时如何保留缩进? [英] How can I retain indentation while using file_get_content with php?

查看:120
本文介绍了在PHP中使用file_get_content时如何保留缩进?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用php中的file_get_contents函数来获取站点的内容.问题是,在我从中获取信息的站点上,信息被整齐地缩进,但是当我检索信息时,它失去了所有缩进.

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.

我正在使用的代码是:

<?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"}

如何保留缩进?

提前谢谢!

顺便说一下,链接和信息来自Facebook的示例页面,而不是真实信息.

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

推荐答案

这与 file_get_contents .它仅取决于页面的Content-Type.原始内容为纯文本,而您的网站输出HTML.

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.

您可以使用:

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

或保留HTML类型,但将输出包装在pre标记中:

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

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

由于您可能想重用该镜像的JSON输出,因此我会选择第一个选项. (但是application/json类型可能更合适.不确定为什么要以固定格式显示它.)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆