PHP&解析JSON响应 [英] PHP & Parsing a JSON response

查看:69
本文介绍了PHP&解析JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to play with a web service via REST.

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

I finally am getting the results I want (or at least I think I am), but am unaware what to do with it. The response format is JSON.. I try outputting it via json_decode() to get it as an array, then I could do something with it.

您可以看到我在回显我正在卷曲的网址时得到了某物"作为响应

You can see that I am getting "something" as a response as I am echoing the url that I am CURL'ing

我知道这是一个教育问题,但这是我的第一时间,因此我们将不胜感激.再次,我的最终目标是明显地以可读格式输出数据.

I know this is a matter of education, but this is my first jaunt at this, so any help is appreciated. Again, my end goal is to obviously output the data in a readable format.

<?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/zh/function.curl-exec.php .我看到的一件值得注意的事情是:

Check here: http://php.net/manual/en/function.curl-exec.php. The one noteworthy thing I saw was this:

成功返回TRUE,失败返回FALSE.但是,如果设置了CURLOPT_RETURNTRANSFER选项,则成功时将返回结果,失败时将返回FALSE.

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

请注意,如果您搜索"curl_get("),就是一个很好的例子.

Note that there is a great example if you search for "curl_get(".

这篇关于PHP&amp;解析JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆