2016-09-09 4 views
1

これは単純な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); 
} 
+1

を印刷JSONは無関係です。いったんデコードされると、他のPHPデータ構造と同様に、PHPのデータ構造になります。その中に「私はjsonだった」という痕跡はまったくありません。あなたは他のPHP構造体のようにデータにアクセスします。 –

+2

シンプル 'echo $ result ['item1'];'、 'echo $ result ['item2'];'は実行します。ところで、それをエンコードするポイントはありませんし、再度それをデコードします。 –

+2

これは 'stdClass Object'と何が関係していますか? 'true'を' json_decode() 'の第2引数として使用すると、オブジェクトではなく連想配列が返されます。 – Barmar

答えて

2

で作業することができget.phpprint_r()を使用しているので、それはJSONを返していません。 json_encode()を使用する必要があります。

if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{ 
    $data = json_decode(file_get_contents("php://input")); 
    echo json_encode($data); 
} 

あなたのcurlスクリプトで正しくデコードできます。

$response = json_decode($json_response, false); 
echo 'Item1 = ' . $response->item1 . '<br>'; 
echo 'Item2 = ' . $response->item2 . '<br>'; 
echo 'Item3 = ' . $response->item3; 
+0

ありがとう。 :X:X –

-1
curl_close($curl); 
$result = json_decode($jsonResponse, true); 
echo $result['item1']; //Echo item 1. 
+0

それは何も返しません –

+0

質問のキーは数値ではありません。 – Barmar

+0

だからこそ私はもう一つの答えを加えた。彼は結果として配列を取得しないように見えます。 'http:// php.net/manual/en/function.json-decode.php'は、' json_decode($ json、true) 'が配列を返します... – user3743266

0

です。

$data = array(
    'item1' => 'value1', 
    'item2' => 'value2', 
    'item3' => 'value3' 
); 
$json=json_encode($data); 
$result=json_decode($json); 
echo $result->item1; 
echo $result->item2; 
echo $result->item3; 

それとも、配列

$json=json_encode($data); 
$result=json_decode($json, true); 
echo $result['item1']; 
echo $result['item2']; 
echo $result['item3']; 
0

データを符号化するために使用json_encode()、その後、JSONを

$data = json_decode(file_get_contents("php://input")); 
    echo json_encode($data); 
関連する問題