如何从CURL解析json响应

wah*_*hid 47 php json curl

我正在使用CURL发送请求.响应dataType是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);

?>
Run Code Online (Sandbox Code Playgroud)

JSON输出:

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

小智 82

如果您的$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);
Run Code Online (Sandbox Code Playgroud)

OUTPUT

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

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

echo $json['MessageID'];
echo $json['SMSError'];
// other stuff
Run Code Online (Sandbox Code Playgroud)

参考文献:


Gus*_*uss 11

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

curl_exec()参考说明:

返回值

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

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

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);
Run Code Online (Sandbox Code Playgroud)

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

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


Dav*_*hen 6

尝试:

$result = curl_exec($cURL);
$result = json_decode($result,true);
Run Code Online (Sandbox Code Playgroud)

现在您可以MessageID从访问$result['MessageID']

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

INSERT INTO `tableName`(`Cancelled`,`Queued`,`SMSError`,`SMSIncommingMessage`,`Sent`,`SentDateTime`) VALUES('?','?','?','?','?');
Run Code Online (Sandbox Code Playgroud)

准备好了