PHP&解析JSON响应

PHP&解析JSON响应

问题描述:

我试图通过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> 

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

成功返回TRUE或失败返回FALSE。但是,如果设置了CURLOPT_RETURNTRANSFER选项,它将在成功时返回结果,在失败时返回FALSE。

请注意,有一个很好的例子,如果你搜索“curl_get(”

下面是一个例子:

$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

这里有一个简单的办法做到这一点不卷曲

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