我怎么能用php读取json响应中的第3项?

时间:2018-02-23 12:37:22

标签: php json curl

我得到了正常的以下代码:

PHP SCRIPT

<div id="txtArea" >
            <textarea style="margin-left:20px;" class="span1 form-control" rows="6" ></textarea>
        </div>
        <div id="buttons">
            <input id="btnApprove" type="button"name="action" value="Create Profile" onclick="return validateCreateStaffProfile()" class="btn btn-default btn-sm_Custom active" />
            <input id="btnReject" type="button" style="margin-left: 30px;" class="btn btn-default btn-sm_Custom active" value="Clear" onclick="return ClearStaffProfileActionDiv();" />
            <input id="btnDelete" type="button" name="action" value="Create Profile" onclick="return validateCreateStaffProfile()" class="btn btn-default btn-sm_Custom active" />
        </div>

返回此JSon:

$url = 'http://wannacharts.com/ch5.php';

//create a new cURL resource
$ch = curl_init($url);


$payload = $data;

//attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

//set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));

//return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//execute the POST request
$result = curl_exec($ch);

//close cURL resource
curl_close($ch);

我需要回应提交的数据&#34;。

我试试:

{"status":200,"status-msg":"OK","data":"1234567"}

但不起作用

3 个答案:

答案 0 :(得分:3)

$result= json_decode($result,true);
echo $result['data'];

您可能会发现它对var_dump($result)很有用,这样如果您不确定JSON如何转换为PHP变量,就可以看到它的结构。

答案 1 :(得分:0)

通过这种方式,您可以访问json中的数据信息:

 $json= json_decode($result,true);

 $obj = json_decode($json);
 print $obj->{'data'}; 

答案 2 :(得分:0)

你可以试试这个

$v = file_get_contents(utf8_encode('http://wannacharts.com/ch5.php'));
$result = json_decode($v, true);
foreach ($result as $k => $v) 
{
  print $v['data'];
}

通常Json的回答是这样的:

{
"glossary": {
    "title": "example glossary",
    "GlossDiv": {
        "title": "S",
        "GlossList": {
            "GlossEntry": {
                "ID": "SGML",
                "SortAs": "SGML",
                "GlossTerm": "Standard Generalized Markup Language",
                "Acronym": "SGML",
                "Abbrev": "ISO 8879:1986",
                "GlossDef": {
                    "para": "A meta-markup language, used to create markup languages such as DocBook.",
                    "GlossSeeAlso": ["GML", "XML"]
                },
                "GlossSee": "markup"
            }
        }
    }
}

因此,如果您想选择GlossDiv标题,您会说

print $v['glossary']['GlossDiv']['title']; //prints out "S"