PHP:从JSON解码获取特定值?

时间:2015-12-02 10:44:21

标签: php arrays json

我正在尝试使用PHP从JSON decode获取特定值。

基本上我有一个由JSON返回的数组,如下所示:

{
  "created": 1326853478,
  "livemode": false,
  "id": "evt_00000000000000",
  "type": "charge.failed",
  "object": "event",
  "request": null,
  "pending_webhooks": 1,
  "api_version": "2015-10-16",
  "data": {
    "object": {
      "id": "ch_00000000000000",
      "object": "charge",
      "amount": 3000,
      "amount_refunded": 0,
      "application_fee": null,
      "balance_transaction": "txn_00000000000000",
      "captured": true,
      "created": 1449010896,
      "currency": "gbp",
      "customer": "cus_00000000000000",
      "description": null,
      "destination": null,
      "dispute": null,
      "failure_code": null,
      "failure_message": null,
      "fraud_details": {
      },
      "invoice": "in_00000000000000",
      "livemode": false,
      "metadata": {
      },
      "paid": false,
      "receipt_email": null,
      "receipt_number": null,
      "refunded": false,
      "refunds": {
        "object": "list",
        "data": [

        ],
        "has_more": false,
        "total_count": 0,
        "url": "/v1/charges/ch_17DN7sFMZc35gfghfghddd8A2gG0Ap8Hg/refunds"
      },
      "shipping": null,
      "source": {
        "id": "card_00000000000000",
        "object": "card",
        "address_city": null,
        "address_country": null,
        "address_line1": null,
        "address_line1_check": null,
        "address_line2": null,
        "address_state": null,
        "address_zip": null,
        "address_zip_check": null,
        "brand": "Visa",
        "country": "US",
        "customer": "cus_00000000000000",
        "cvc_check": "pass",
        "dynamic_last4": null,
        "exp_month": 12,
        "exp_year": 2033,
        "funding": "credit",
        "last4": "4242",
        "metadata": {
        },
        "name": "useremail@yahoo.co.uk",
        "tokenization_method": null
      },
      "statement_descriptor": null,
      "status": "succeeded"
    }
  }
}

所以,我需要做的是获取"name": "useremail@yahoo.co.uk",的值,这是用户的电子邮件,这样我就可以在我这边做一些数据库更改。

我创建了这段代码:

$input = @file_get_contents("php://input");
$event_json = json_decode($input);

// Do something with $event_json


//print_r($event_json);


$user = $event_json->name;

http_response_code(200); // PHP 5.4 or greater


$file = fopen("file.txt","w");
fwrite($file,$user);
fclose($file);

因此,正如您在上面所看到的,变量$user应写入file.txt,但不会将任何内容写入file.txt。

我继续测试整个阵列并尝试在file.txt中编写整个数组,它的工作原理非常好。

$file = fopen("file.txt","w");
fwrite($file,$input);
fclose($file);

我也尝试从JSON数组中获取名称值,如下所示:

$json = json_decode($input, true);
$user = $json['name'];

并且仍未在我的file.txt中写入任何内容!

有人可以就此问题提出建议吗?

我做错了什么或遗失了什么?

0 个答案:

没有答案