请找到json iam接收:
{
"batchcomplete":"",
"continue":{
"sroffset":10,
"continue":"-||"
},
"query":{
"searchinfo":{
"totalhits":1937
},
"search":[
{
"ns":0,
"title":"India",
"pageid":15557,
"size":213703,
"wordcount":30816,
"snippet":"<span class=\"searchmatch\">India</span> (Hindi: \u092d\u093e\u0930\u0924 or Bharat) is the largest country in the Indian subcontinent and shares borders with Pakistan to the northwest, China and Nepal to",
"timestamp":"2018-05-27T12:16:15Z"
},
{
"ns":0,
"title":"Southern India",
"pageid":33554,
"size":20350,
"wordcount":2534,
"snippet":"South <span class=\"searchmatch\">India</span> includes five major states in peninsular <span class=\"searchmatch\">India</span> and the two island groups of Lakshadweep in the Arabian Sea on the West Coast of <span class=\"searchmatch\">India</span> and Andaman",
"timestamp":"2018-05-13T14:30:50Z"
}}
我试图使用php检索数据。
我的PHP代码如下。
curl_setopt ($curl, CURLOPT_URL, 'https://en.wikivoyage.org/w/api.php?action=query&list=search&srwhat=text&srsearch=India&format=json');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$xml = curl_exec ($curl);
if ($xml === false) {
die('Error fetching data: ' . curl_error($curl));
}
curl_close ($curl);
echo htmlspecialchars("$xml", ENT_QUOTES);
$data = json_decode($xml);
foreach ($data->query as $country)
{
echo $country->searchinfo;
}
但我在这行收到错误.echo $ country-&gt; searchinfo;该错误表明未定义的属性:stdClass :: $ searchinfo。
我正在尝试仅检索片段变量(第一个)
有人可以帮助我。
答案 0 :(得分:0)
1。$data->queryfo
需要$data->query
2.您必须像这样更改foreach()
: -
foreach ($data->query->search as $country)
{
echo $country->snippet;echo PHP_EOL;
}
注意: - 我已按您所说的I am trying to receive the snippet and not totalhits