简体   繁体   English

使用PHP从外部URL获取Json对象

[英]Get Json Object from external URL with PHP

I have an URL that returns the JSON object below: 我有一个网址,返回以下JSON对象:

{
    "addressList": {
        "addresses": [
            {
                "id": 0000000,
                "receiverName": "Name Example",
                "country": {
                    "id": "BRA",
                    "name": "Brasil"
                },
                "state": {
                    "id": "SP"
                },
                "city": "São Paulo",
                "zipcode": "00000000",
                "type": "Residential",
                "street": "000, St Example",
                "number": 00,
                "neighborhood": "Example",
                "hash": "1bf09357",
                "defaultAddress": false,
                "notReceiver": false
            }
        ]
    }
}

I want to get the state value, how can I retrieve that with PHP? 我想获取state值,如何使用PHP检索state值?

I tried, something like this, but I couldn't get the state value, that should be SP in this case. 我尝试过类似的操作,但无法获取state值,在这种情况下应为SP

$string = '{ "addressList": { "addresses": [ { "id": xxxxxx, "receiverName": "XXXXX XXXXX", "country": { "id": "BRA", "name": "Brasil" }, "state": { "id": "SP" }, "city": "São Paulo", "zipcode": "03164xxx", "type": "Residential", "street": "Rua xxx", "number": xx, "neighborhood": "xxxxx", "hash": "xxxxx", "defaultAddress": false, "notReceiver": false } ] } }';

        $json_o = json_decode($string);

        $estado = $json_o->state;

How can I achieve the result I want? 如何获得想要的结果?

Your JSON is not valid - you can validate it on jsonlint.com ( it's invalid due to incorrectly formatted numeric values - "id" : 000000 ). 您的JSON无效-您可以在jsonlint.com上进行验证( 由于格式错误的数字值- "id" : 000000它无效 )。

From then on, you can decode the value and access your data: 从那时起,您可以解码该值并访问您的数据:

$json_o = json_decode($string);

$estado = $json_o->addressList->addresses[0]->state->id;

If you don't have access to the code that generates the JSON, you can attempt to run a regex to match, replace & wrap the numerical values with " : 如果您无权访问生成JSON的代码,则可以尝试运行正则表达式来匹配,替换数字值并将其包装为"

$valid_json = preg_replace("/\b(\d+)\b/", '"${1}"', $str);

Note: The above is just an example - you'll have to figure out a case where a numerical value is already wrapped by " . 注意: 以上仅是一个示例-您必须弄清楚数字值已经由"括起来的情况。

Your JSON has a couple of syntax errors: 您的JSON有两个语法错误:

"id":     0000000
"number": 00

JSON doesn't support leading zeros. JSON不支持前导零。 If precise formatting is important, use strings: 如果精确格式很重要,请使用字符串:

"number": "00"
"id":     "0000000"

Alternatively, use well-formed integers in the JSON (saves space) and convert them to formatted strings in PHP. 或者,在JSON(节省空间)中使用格式正确的整数,然后将其转换为PHP中的格式化字符串。

Once you've fixed your JSON, you can access the state->id value of the first address as I do below. 修复JSON之后,您可以按以下步骤访问第一个地址的state->id值。 When you decode JSON from an untrusted source, be prepared to do some error handling: 当您从不受信任的来源解码JSON时,请做好一些错误处理的准备:

$json_string ="..."; //your source, to be decoded

$json_o= json_decode($json_string);

if(is_null($json_o)): //there was an error decoding        
    $errno = json_last_error();
    $err_msg = json_last_error_msg();
    die("Json decode failed: Error #$errno: $err_msg");
endif;
//we get here if json_decode succeeded. To get "SP", do...
$stateID = $json_o->addressList->addresses[0]->state->id;

尝试:

$json_o = json_decode($string, true); $estado = $json_o['addressList']['addresses'][0]['state']['id'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM