2013-08-20 123 views
0

您好我正在嘗試使用此網址從維基百科進行此api調用,但它說它是空的時,我轉儲該變量。這個函數適用於我的其他json api調用,但不適用於此,我手動在broswer中測試它,它給了我一個結果。這是我嘗試JSON解碼捲曲問題

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

} 
+0

什麼 「不工作」 是什麼意思?它輸出「我不工作」或什麼? – zerkms

回答

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; 

} 
0

您應該考慮使用http_build_query()建立的網址:

$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', 
));