简体   繁体   English

PHP和解析JSON响应

[英]PHP & Parsing a JSON response

I'm trying to play with a web service via REST. 我正在尝试通过REST来使用Web服务。

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. 响应格式为JSON。我尝试通过json_decode()输出以将其作为数组获取,然后可以对其进行处理。

You can see that I am getting "something" as a response as I am echoing the url that I am CURL'ing 您会看到我在回显我正在卷曲的URL时得到了“响应”

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>

Check here: http://php.net/manual/en/function.curl-exec.php . 在这里检查: http : //php.net/manual/en/function.curl-exec.php The one noteworthy thing I saw was this: 我看到的一件值得注意的事情是:

Returns TRUE on success or FALSE on failure. 成功返回TRUE,失败返回FALSE。 However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure. 但是,如果设置了CURLOPT_RETURNTRANSFER选项,则成功时将返回结果,失败时将返回FALSE。

Note that there is a great example if you search for "curl_get(". 请注意,如果您搜索“ curl_get(”,则是一个很好的例子。

Here's an example: 这是一个例子:

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

$jsonArray = json_decode($json);

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

Here's a simplified way to do it without cURL 这是一种无需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