2012-05-08 32 views
1

我有條紋json,我試圖解碼它json_decode。解碼條紋json json_decode不工作

我沒有收到錯誤。只是沒有回報。我從條紋中獲取數據,我只是無法解碼它。

{ 
    "created":1326853478, 
    "data":{ 
     "object":{ 
     "amount":4500, 
     "card":{ 
      "country":"US", 
      "cvc_check":"pass", 
      "exp_month":7, 
      "exp_year":2014, 
      "fingerprint":"9aQtfsI8a17zjEZd", 
      "id":"cc_00000000000000", 
      "last4":"9782", 
      "object":"card", 
      "type":"Visa" 
     }, 
     "created":1322700852, 
     "currency":"usd", 
     "disputed":false, 
     "fee":0, 
     "id":"ch_00000000000000", 
     "livemode":false, 
     "object":"charge", 
     "paid":true, 
     "refunded":true 
     } 
    }, 
    "id":"evt_00000000000000", 
    "livemode":false, 
    "type":"charge.refunded" 
} 

// retrieve the request's body and parse it as JSON 
$body = @file_get_contents('php://input'); 

$event_json = json_decode($body,true); 
print_r($event_json); 

任何想法?

+5

呀。刪除隱藏任何錯誤消息的字符。 –

+0

Igancio指的是@字符。 – Hamish

+0

也可以用'json_last_error()'和/或http://jsonlint.com/來檢查,你可能在那裏有一個UTF-8 BOM。 – mario

回答

1

在這裏,我跑了這一點:

<?php 
    $data = '{ "created": 1326853478, "data": { "object": { "amount": 4500, "card": { "country": "US", "cvc_check": "pass", "exp_month": 7, "exp_year": 2014, "fingerprint": "9aQtfsI8a17zjEZd", "id": "cc_00000000000000", "last4": "9782", "object": "card", "type": "Visa" }, "created": 1322700852, "currency": "usd", "disputed": false, "fee": 0, "id": "ch_00000000000000", "livemode": false, "object": "charge", "paid": true, "refunded": true } }, "id": "evt_00000000000000", "livemode": false, "type": "charge.refunded" }'; 

    $arr = json_decode($data, true); 

    print_r($arr); 

?> 

和它的工作。所以,理論上你應該能夠使用:

<?php 

    $arr = json_decode(file_get_contents('php://input'), true); 

    print_r($arr); 

?> 

正如伊格納西奧巴斯克斯 - 艾布拉姆斯說,不要因爲它掩蓋了錯誤信息,並使其更難調試使用「@」字符。

我也會檢查你的PHP版本。 json_decode()僅在5.2.0及更高版本上可用。

1

php://input流允許您從請求主體讀取原始數據。這些數據將是一個字符串,根據什麼樣的值都在請求,看起來像:

"name=ok&submit=submit" 

這是 JSON,因此不會解碼爲JSON的方式,你expect.The json_decode()函數返回null如果它不能被解碼。

你從哪裏得到上面發佈的JSON?這是你需要傳遞給json_decode()的價值。

如果在請求中傳遞JSON,就像在回調的實例中一樣,您仍然需要解析該部分才能獲得JSON。如果php://input流爲您提供name = ok & submit = submit & json = {「created」:1326853478}然後您必須將其解析出來。您可以使用this function從PHP手冊,以單獨的值,如$_POST陣列工作:

<?php 
    // Function to fix up PHP's messing up POST input containing dots, etc. 
    function getRealPOST() { 
     $pairs = explode("&", file_get_contents("php://input")); 
     $vars = array(); 
     foreach ($pairs as $pair) { 
     $nv = explode("=", $pair); 
     $name = urldecode($nv[0]); 
     $value = urldecode($nv[1]); 
     $vars[$name] = $value; 
     } 
     return $vars; 
    } 
?> 

要使用它:

$post = getRealPOST(); 
$stripe_json = $post['json']; 
$event_json = json_decode($stripe_json);