0

嗨,我正在尝试使用此 url 从维基百科进行此 api 调用,但是当我转储变量时它说它为空。此函数适用于我的其他 json api 调用,但不适用于此,我在浏览器中手动对其进行了测试,它给了我一个结果。这是我的尝试

$url = 'http://en.wikipedia.org/w/api.php?action=query&format=json&titles=Image:Romerolagus diazi (dispale) 001.jpg&prop=imageinfo&iiprop=url'; 

 $result = apicall($url);
 var_dump($result);     

 function apicall($url){

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_USERAGENT, 'MyBot/1.0 (http://www.mysite.com/)');

  $result = curl_exec($ch);

  if (!$result) {
    exit('cURL Error: '.curl_error($ch));
  }

  $var = json_decode($result);


  return $var;

}
4

2 回答 2

1

urlencode()问题,这样修改

    <?php
$url = 'http://en.wikipedia.org/w/api.php'; 
$titles = urlencode('Image:Romerolagus diazi (dispale) 001.jpg');
$queryStr = 'action=query&format=json&titles='.$titles.'&prop=imageinfo&iiprop=url';
$url = $url . '?' . $queryStr;

 $result = apicall($url);
 var_dump($result);     

 function apicall($url){

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');

  $result = curl_exec($ch);

  if (!$result) {
    exit('cURL Error: '.curl_error($ch));
  }

  var_dump($result);
  $var = json_decode($result);


  return $var;

}
于 2013-08-20T03:14:26.933 回答
0

您应该考虑使用http_build_query()来构建 URL:

$url = 'http://en.wikipedia.org/w/api.php?' . http_build_query(array(
    'action' => 'query',
    'format' => 'json',
    'titles' => 'Image:Romerolagus diazi (dispale) 001.jpg',
    'prop' => 'imageinfo',
    'iiprop' =>  'url',
));
于 2013-08-20T03:17:26.660 回答