无法使用curl检索JSON以在php中解析

时间:2017-04-28 10:39:51

标签: php json curl

我正在尝试通过curl在PHP中解析和解析JSON。我无法解析响应,并看到它转储到我的屏幕上。这是示例代码。

<?php

$url = 'XXXXXXXXXXXXXXXXXXXXX';

$cURL = curl_init();

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

curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'X-Mashape-Key: XXXXXXXXXXXXXXXXXXXXXXXXX',
'Accept: application/json'
));

$result = curl_exec($cURL); ## this seems to be the line printing the response?

curl_close($cURL);

echo "<br />--------------------------------------------------------<br />";

var_dump($cURL);

echo "<br />--------------------------------------------------------<br />";

var_dump($result);

echo "<br />--------------------------------------------------------<br />";

$json = json_decode($result);

echo "<br />--------------------------------------------------------<br />";

print_r($json);

echo "<br />--------------------------------------------------------<br />";

echo $json->word;
echo $json->definitions[0]->definition;

echo "<br />--------------------------------------------------------<br />";

?>

输出是:

{"word":"incredible","definitions":[{"definition":"beyond belief or understanding","partOfSpeech":"adjective"}]}
--------------------------------------------------------
resource(2) of type (Unknown) 
--------------------------------------------------------
bool(true) 
--------------------------------------------------------

--------------------------------------------------------
1
--------------------------------------------------------

--------------------------------------------------------

在我的第一个echo语句之前看看我的JSON是如何出现在屏幕上的?为什么会这样?

2 个答案:

答案 0 :(得分:3)

cURL不会返回转移,但会输出。您不得输出转移。添加具有true值的CURLOPT_RETURNTRANSFER选项。同样在响应JSON中,定义不是它的数组对象,它也将在php中解析为数组。此外,响应中没有attachments键,因此您无法访问它。

$url = 'XXXXXXXXXXXXXXXXXXXXX';

$cURL = curl_init();

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

curl_setopt($cURL, CURLOPT_HTTPHEADER, array(
'X-Mashape-Key: XXXXXXXXXXXXXXXXXXXXXXXXX',
'Accept: application/json'
));

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1); // add this line to catch your response with curl_exec function. 

$result = curl_exec($cURL); 

$json = json_decode($result);

print_r($json); // this will print parsed json.

echo $json->word;
echo $json->definitions[0]->definition; // Get First Entry of definitions

答案 1 :(得分:0)

使用$json = json_decode($json);然后您可以使用$json['word'],依此类推。