难以在卷发中恢复JSON以在PHP中解析



我正在尝试通过卷发在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
--------------------------------------------------------
--------------------------------------------------------

在我的第一个回声语句之前,请查看我的JSON在屏幕上出现的方式吗?为什么会发生?

curl不返回传输,但会输出。您不得输出转移。添加具有真实值的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

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

最新更新