2011-08-18 190 views
2

我試圖通過REST與Web服務一起玩。PHP&解析JSON響應

我終於得到了我想要的結果(或者至少我認爲我是),但我並不知道如何處理它。響應格式是JSON ..我嘗試通過json_decode()輸出它作爲一個數組,然後我可以做一些事情。

你可以看到,我正在「東西」作爲迴應,因爲我呼應,我CURL'ing

我知道這是教育的問題的URL,但是這是我第一次短途旅遊,在這,所以任何幫助表示讚賞。再次,我的最終目標是明顯輸出可讀格式的數據。

<?php 

    if(isset($_GET['word'])) 
    { 
     $result= get_response_json($_GET['word']); 
    } else {$result = "";} 

    function get_response_json($word) 
    { 
     $postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word); 
     echo $postURL; 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, $postURL); 
     curl_setopt($ch, CURLOPT_HEADER, false); 
     //curl_setopt($ch, CURLOPT_POST, true); 
     $result = curl_exec($ch); 
     curl_close($ch); 

     return $result; 
    } 

?> 

<html> 
    <title>Test Rhyme</title> 
<body> 

    <form action="<?=$_SERVER['PHP_SELF'];?>" method="get"> 
     <input type="input" name="word" /> 
     <input type="submit" value="Submit" /> 
    </form> 
    <div id="results"> 
     <?php 
      print_r(json_decode($result, true)); 
     ?> 
    </div>  
</body> 

</html> 

回答

3

入住這裏:http://php.net/manual/en/function.curl-exec.php。我看到的一件值得注意的事情是:

成功返回TRUE或失敗返回FALSE。但是,如果設置了CURLOPT_RETURNTRANSFER選項,它將在成功時返回結果,在失敗時返回FALSE。

請注意,有一個很好的例子,如果你搜索「curl_get(」

1

下面是一個例子:

$json = '[ 
    { 
     "ID": "1001", 
     "Phone": "5555555555" 
    } 
]'; 

$jsonArray = json_decode($json); 

foreach($jsonArray as $value){ 
    $id = $value->ID; 
    $phone = $value->Phone; 
} 
+0

語法錯誤:) – genesis

+0

哦,是嗎?因爲我只是從我的網站上使用它,也許是在我弄亂了我搞砸了的信息的同時,注意指出它呢? –

+0

http://sandbox.phpcode.eu/g/d31ce.php - 自己找,如果你是程序員 – genesis

0

這裏有一個簡單的辦法做到這一點不捲曲

function get_response_json($word) 
    { 
     $postURL = "http://rhymebrain.com/talk?function=getRhymes&word=".urlencode($word); 
     $json = file_get_contents($postURL); 
     return $json; 
    }