これは単純なJSONですが、項目にアクセスできません。 JSONをget.phpに送信して、JSONをprint_rだけ解析し、JSON応答を解析することに問題があります。JSONをPHP(stdClassオブジェクト)にエコーする方法は?
マイコード:
$url = "http://localhost/get.php";
$data = array(
'item1' => 'value1',
'item2' => 'value2',
'item3' => 'value3'
);
$content = json_encode($data);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($status == 201) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, false);
$result=json_encode($json_response);
$data=json_decode($result);
がどのように私は1又は2をエコーすることができますか?
これは、あなたがstdClassのを取得するためjson_decode関数の中で第二のparamを設定する必要はありませんget.php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents("php://input"));
print_r($data);
}
を印刷JSONは無関係です。いったんデコードされると、他のPHPデータ構造と同様に、PHPのデータ構造になります。その中に「私はjsonだった」という痕跡はまったくありません。あなたは他のPHP構造体のようにデータにアクセスします。 –
シンプル 'echo $ result ['item1'];'、 'echo $ result ['item2'];'は実行します。ところで、それをエンコードするポイントはありませんし、再度それをデコードします。 –
これは 'stdClass Object'と何が関係していますか? 'true'を' json_decode() 'の第2引数として使用すると、オブジェクトではなく連想配列が返されます。 – Barmar