2012-01-04 86 views
1

我想從另一個頁面拉出一個JSON對象,然後將它分解成片段和值給我的php文檔的變量並用它們填充頁面。php,JSON:cURL對象不能用PHP編輯

我遇到的問題是,當curl_exec調用打印JSON對象時,我無法對此做任何事情。下面是我的代碼:

$json_url = "localhost:8080/query"; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
curl_setopt($ch, CURLOPT_URL, $json_url); 
curl_setopt($ch, CURLOPT_USERPWD, $user.":".$pass); 
$result = json_decode(curl_exec($ch)); 
var_dump ($result); 

$curl_errno = curl_errno($ch); 
$curl_error = curl_error($ch); 

curl_close($ch); 

// ON SUCCESS 

$json_a = $result[10]; 
var_dump ($json_a); 

這裏是一片結果的樣本:

["4"]=> array(2) { [0]=> int(1325003843) [1]=> array(2) { [0]=> int(47) [1]=> array(17) { [0]=> array(2) { [0]=> int(0) [1]=> int(1) } [1]=> array(2) { [0]=> int(17) [1]=> int(44) } [2]=> array(2) { [0]=> int(3) [1]=> int(4) } [3]=> array(2) { [0]=> int(3) [1]=> int(4) } [4]=> array(2) { [0]=> int(3) [1]=> int(4) } [5]=> array(2) { [0]=> int(3) [1]=> int(4) } [6]=> array(2) { [0]=> int(3) [1]=> int(4) } [7]=> array(2) { [0]=> int(3) [1]=> int(4) } [8]=> array(2) { [0]=> int(3) [1]=> int(4) } [9]=> array(2) { [0]=> int(3) [1]=> int(4) } [10]=> array(2) { [0]=> int(3) [1]=> int(4) } [11]=> array(2) { [0]=> int(3) [1]=> int(4) } [12]=> array(2) { [0]=> int(3) [1]=> int(4) } [13]=> array(2) { [0]=> int(2) [1]=> int(3) } [14]=> array(2) { [0]=> int(2) [1]=> int(3) } [15]=> array(2) { [0]=> int(2) [1]=> int(3) } [16]=> array(2) { [0]=> int(2) [1]=> int(3) } } } } 

後續代碼var_dump($結果);返回int(1),另一個var_dump返回NULL。 curl_exec實際上是打印JSON對象,所以我知道它至少可以抓住它。非常感謝您提供的任何幫助!

回答

1

你也可以只像做

$json_url = "localhost:8080/query"; 
// $protocol should be the protocol used, ie. 'ftp://', 'http://' or 'https://' 
// to produce an URL like 'ftp://user:[email protected]:8080/query' 
$result = file_get_contents($protocol . $user.":".urlencode($pass) . '@' . $json_url); 

if($result !== false) { // ON SUCCESS 
    $result = json_decode($result, true); 
    var_dump ($result); 

    if(isset($result[10])) { // If index 10 of $result exists 
    $json_a = $result[10]; 
    var_dump ($json_a); 
    } 
} else { 
    // error occured 
} 
換句話說
+0

非常感謝!這會取代上面的整個代碼段?另外,$協議是什麼?非常感謝,讓我知道如果你需要我的任何其他信息! – prosborne 2012-01-04 18:38:25

+0

那麼,取決於你的'$ json_url'包含的內容。如果你可以在上面的代碼中加入var_dumps,我會相應地更新我的答案。 – Flygenring 2012-01-04 18:42:03

+0

好吧,我更新了問題,然後還添加了部分結果。這是一個非常巨大的對象,所以包括整個事情將很難...... – prosborne 2012-01-04 18:51:37

3

將CURLOPT_RETURNTRANSFER設置爲false,curl_exec只返回true或false。 將CURLOPT_RETURNTRANSFER設置爲true,並且curl_exec應該爲您返回結果。

+0

,如果returntransfer是假的,捲曲將輸出結果到客戶端,而不是將其返回到腳本。 – 2012-01-04 18:23:08

+0

好的,非常感謝!現在,當我解碼$ ch時,第一個var_dump會打印「array(2)..」,然後將JSON對象作爲數組打印。但我的第二個var_dump仍顯示爲空。 – prosborne 2012-01-04 18:30:20

+0

你可以發佈第一個var_dump的輸出嗎?看起來像'$ result'是一個只有兩個項目的數組,所以引用索引可能應該返回null? – Flygenring 2012-01-04 18:36:40