繁体   English   中英

PHP和解析JSON响应

[英]PHP & Parsing a JSON response

我正在尝试通过REST来使用Web服务。

我终于得到了想要的结果(或者至少我认为是),但是不知道该怎么做。 响应格式为JSON。我尝试通过json_decode()输出以将其作为数组获取,然后可以对其进行处理。

您会看到我在回显我正在卷曲的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;
}

这是一种无需cURL的简化方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM