php 如何解析来自 CURL 的 json 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17016506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:06:17  来源:igfitidea点击:

How to parse json response from CURL

phpjsoncurl

提问by wahid

I am using CURL to send a request. The response dataType is json. How can I parse this data and insert it into the database?

我正在使用 CURL 发送请求。响应数据类型是json。如何解析这些数据并将其插入到数据库中?

<?php

$url = 'http://sms2.cdyne.com/sms.svc/SimpleSMSsendWithPostback?        PhoneNumber=18887477474&Message=test&LicenseKey=LICENSEKEY';

$cURL = curl_init();

curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);

curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Accept: application/json'
));

$result = curl_exec($cURL);

curl_close($cURL);



print_r($result);

?>

JSON Output:

JSON 输出:

{
    "Cancelled": false,
    "MessageID": "402f481b-c420-481f-b129-7b2d8ce7cf0a",
    "Queued": false,
    "SMSError": 2,
    "SMSIncomingMessages": null,
    "Sent": false,
    "SentDateTime": "/Date(-62135578800000-0500)/"
}

回答by

If your $resultvariable is a string json like, you must use json_decodefunction to parse it as an objector array:

如果您的$result变量是类似 json 的字符串,则必须使用json_decode函数将其解析为对象数组

$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';
$json = json_decode($result, true);
print_r($json);

OUTPUT

输出

Array
(
    [Cancelled] => 
    [MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
    [Queued] => 
    [SMSError] => 2
    [SMSIncomingMessages] => 
    [Sent] => 
    [SentDateTime] => /Date(-62135578800000-0500)/
)

Now you can work with $jsonvariable as an array:

现在您可以将$json变量作为数组使用:

echo $json['MessageID'];
echo $json['SMSError'];
// other stuff


References:

参考:

回答by Dave Chen

Try:

尝试:

$result = curl_exec($cURL);
$result = json_decode($result,true);

Now you can access MessageIDfrom $result['MessageID'].

现在您可以MessageID$result['MessageID'].

As for the database, it's simply using a query like so:

至于数据库,它只是使用如下查询:

INSERT INTO `tableName`(`Cancelled`,`Queued`,`SMSError`,`SMSIncommingMessage`,`Sent`,`SentDateTime`) VALUES('?','?','?','?','?');

Prepared.

准备好了。

回答by Guss

The main problem with your example code is that the $resultvariable you use to store the output of curl_exec()does not contain the body of the HTTP response - it contains the value true. If you try to print_r()that, it will just say "1".

您的示例代码的主要问题是$result您用来存储输出的变量curl_exec()不包含 HTTP 响应的正文 - 它包含值true。如果你尝试print_r()这样做,它只会说“1”。

The curl_exec()referenceexplains:

curl_exec()参考说明:

Return Values

Returns TRUEon success or FALSEon failure. However, if the CURLOPT_RETURNTRANSFERoption is set, it will return the result on success, FALSEon failure.

返回值

TRUE成功或FALSE失败时返回。但是,如果CURLOPT_RETURNTRANSFER设置了该选项,它将在成功或FALSE失败时返回结果。

So if you want to get the HTTP response body in your $resultvariable, you must first run

所以如果你想在你的$result变量中获取 HTTP 响应体,你必须首先运行

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

After that, you can call json_recode()on $result, as other answers have noted.

在这之后,你可以叫json_recode()$result,因为其他答案已经指出。

On a general note - the curl library for PHP is useful and has a lot of features to handle the minutia of HTTP protocol (and others), but if all you want is to GETsome resource or even POSTto some URL, and read the response - then file_get_contents()is all you'll ever need: it is much simpler to use and have much less surprising behavior to worry about.

一般而言 - PHP 的 curl 库很有用,并且具有许多功能来处理 HTTP 协议(​​和其他协议)的细节,但是如果您想要的只是GET某个资源甚至POST某个 URL,并读取响应 -然后file_get_contents()就是你所需要的:它使用起来要简单得多,而且不需要担心的令人惊讶的行为也少得多。