使用PHP检索JSON时出错 [英] Error retrieving json with php

查看:104
本文介绍了使用PHP检索JSON时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用PHP检索json信息时遇到问题.

I've some problem retrieving json information with a PHP.

我创建了一个简单的php页面,该页面返回一个json:

I've created a simple php page that returns a json:

$data = array(
    'title' => 'Simple title'
);
print json_encode($data);

然后在另一页中,我尝试将该数组作为对象:

And in another page I try to get that array as an object:

$content = file_get_contents($url);
$json_output = json_decode($content, true); 

switch(json_last_error())
{
    case JSON_ERROR_DEPTH:
        echo ' - Maximum stack depth exceeded';
        break;
    case JSON_ERROR_CTRL_CHAR:
        echo ' - Unexpected control character found';
        break;
    case JSON_ERROR_SYNTAX:
        echo ' - Syntax error, malformed JSON';
        break;
    case JSON_ERROR_NONE:
        echo ' - No errors';
        break;
}

问题是这种方法存在错误:我收到"JSON_ERROR_SYNTAX",因为在执行"file_get_contents"功能后,字符串开头有一个未知字符.

The problem is that there is an error with this approach: I receive a "JSON_ERROR_SYNTAX" because after "file_get_contents" function I have an unknown character at the beginning of the string.

如果我在Notepad ++上复制/粘贴它,则看不到:

If I copy/paste it on Notepad++ I didn't see:

{"title":"Simple title"}

但我看到了

?{"title":"Simple title"}

有人可以帮我吗?

推荐答案

请确保两个脚本的编码均相同-如果使用的是UTF,请确保它们在文件的开头都没有字节顺序标记(BOM).

Make sure both your scripts have same encoding - and if it's UTF make sure they are without Byte Order Mark (BOM) at very begin of file.

这篇关于使用PHP检索JSON时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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