// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL,
"https://uselessfacts.jsph.pl/random.json?" .
"language=en");
// $output contains the output json
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$outputArray = json_decode($output, true);
echo "<br><br><br><br>" . $outputArray[0]->text;
我有错误 -
"试图检索非对象。"
我认为解码的对象是混合对象,而不是数组。这使它更加复杂。
我只是试图检索属于indice"文本"的字符串。有6个索引,我正在尝试检索第二个索引,然后打印它。我考虑使用使用foreach循环或循环,也许我需要一个fiel循环,并带有单个if语句。我认为最简单的方法只是直接访问索引并将其存储在字符串中。
感谢帮助。
请参阅以下代码。我对此进行了一些改动,并解释了这一点。
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL,
"https://uselessfacts.jsph.pl/random.json?" .
"language=en");
// set the return value to ture as it was returning bool for success
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// set the return response to json type
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
// $output contains the output json
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$outputArray = json_decode($output, true);
echo "<br><br><br><br>" . $outputArray['text'];