user2604754
user2604754

Reputation: 55

JSON decode curl issue

Hi I'm trying to make this api call from wikipedia using this url, however it says it's null when I dump the variable. This function works for my other json api calls but not for this, I tested it in the broswer manually it gives me a result. Here is my attempt

$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;

}

Upvotes: 0

Views: 166

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173662

You should consider using http_build_query() to build the 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',
));

Upvotes: 0

Larry.Z
Larry.Z

Reputation: 3724

urlencode() problem, modify like this

    <?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;

}

Upvotes: 1

Related Questions