如何使用 PHP 从 JSON 中提取数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29308898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:21:06  来源:igfitidea点击:

How do I extract data from JSON with PHP?

phpjson

提问by user3942918

This is intended to be a general reference question and answer covering many of the never-ending "How do I access data in my JSON?"questions. It is here to handle the broad basics of decoding JSON in PHP and accessing the results.

这是一个通用的参考问题和答案,涵盖了许多永无止境的“如何访问我的 JSON 中的数据?” 问题。它在这里处理在 PHP 中解码 JSON 和访问结果的广泛基础知识。

I have the JSON:

我有 JSON:

{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}

How do I decode this in PHP and access the resulting data?

如何在 PHP 中解码并访问结果数据?

回答by user3942918

Intro

介绍

First off you have a string. JSON is not an array, an object, or a data structure. JSONis a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

首先你有一个字符串。JSON 不是数组、对象或数据结构。JSON是一种基于文本的序列化格式 - 所以是一个花哨的字符串,但仍然只是一个字符串。在 PHP 中使用json_decode().

 $data = json_decode($json);

Therein you might find:

您可能会在其中找到:

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

这些是可以用 JSON 编码的东西。或者更准确地说,这些是可以用 JSON 编码的东西的 PHP 版本。

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

他们没有什么特别之处。它们不是“JSON 对象”或“JSON 数组”。您已经解码了 JSON - 现在您拥有基本的日常 PHP 类型

Objects will be instances of stdClass, a built-in class which is just a generic thingthat's not important here.

对象将是stdClass 的实例,这是一个内置类,它只是一个通用的东西,在这里并不重要。



Accessing object properties

访问对象属性

You access the propertiesof one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

您访问的属性的其中之一的对象,你会以同样的方式用于任何其他目的,如公共非静态属性$object->property

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut


Accessing array elements

访问数组元素

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

您可以像访问任何其他数组一样访问这些数组之一的元素,例如$array[0].

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

Iterate over it with foreach.

用 迭代它foreach

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

Glazed
Chocolate with Sprinkles
Maple

淋上 枫糖的釉面
巧克力

Or mess about with any of the bazillion built-in array functions.

或者搞乱任何无数的内置数组函数



Accessing nested items

访问嵌套项

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc.

对象的属性和数组的元素可能是更多的对象和/或数组——您可以像往常一样简单地继续访问它们的属性和成员,例如$object->array[0]->etc.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004


Passing trueas the second argument to json_decode()

true作为第二个参数传递给json_decode()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key'].

当你这样做时,你会得到关联数组而不是对象——带有键字符串的数组。您再次像往常一样访问其中的元素,例如$array['key'].

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple


Accessing associative array items

访问关联数组项

When decoding a JSON objectto an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value)syntax, eg

将 JSON对象解码为关联 PHP 数组时,您可以使用以下foreach (array_expression as $key => $value)语法迭代键和值,例如

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}

Prints

印刷

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'

键 'foo' 的值为 'foo value'
键 'bar' 的值为 'bar value'
键 'baz' 的值为 'baz value'



Don't know how the data is structured

不知道数据结构如何

Read the documentation for whatever it is you're getting the JSON from.

阅读文档以了解您从中获取 JSON 的内容。

Look at the JSON - where you see curly brackets {}expect an object, where you see square brackets []expect an array.

看看 JSON - 你看到大括号{}期望一个对象,你看到方括号[]期望一个数组。

Hit the decoded data with a print_r():

用 a 击中解码的数据print_r()

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

print_r($yummy);

and check the output:

并检查输出:

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

它会告诉你哪里有对象,哪里有数组,以及它们成员的名称和值。

If you can only get so far into it before you get lost - go that far and hit thatwith print_r():

如果你只能得到这么远到它,你迷路之前-走那么远,命中print_r()

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

这个方便的交互式 JSON 资源管理器中查看它。

Break the problem down into pieces that are easier to wrap your head around.

将问题分解成更容易解决问题的部分。



json_decode()returns null

json_decode()返回 null

This happens because either:

发生这种情况是因为:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msgor put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().
  1. JSON 完全由null.
  2. JSON 无效 - 检查结果json_last_error_msg或通过JSONLint 之类的东西
  3. 它包含嵌套超过 512 层的元素。可以通过将整数作为第三个参数传递给 来覆盖此默认最大深度json_decode()

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.

如果您需要更改最大深度,您可能解决了错误的问题。找出为什么您会获得如此深度嵌套的数据(例如,您正在查询的生成 JSON 的服务存在错误)并避免这种情况发生。



Object property name contains a special character

对象属性名称包含特殊字符

Sometimes you'll have an object property name that contains something like a hyphen -or at sign @which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

有时,您会拥有一个对象属性名称,其中包含不能在文字标识符中使用的连字符-或 at 符号之类的@内容。相反,您可以使用花括号内的字符串文字来解决它。

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

If you have an integer as property see: How to access object properties with names like integers?as reference.

如果您有一个整数作为属性,请参阅:如何访问具有整数等名称的对象属性?作为参考。



Someone put JSON in your JSON

有人把 JSON 放在你的 JSON 中

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

这很荒谬,但它确实发生了 - 在您的 JSON 中有 JSON 编码为字符串。解码,像往常一样访问字符串,解码那个,最终得到你需要的。

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed


Data doesn't fit in memory

数据不适合内存

If your JSON is too large for json_decode()to handle at once things start to get tricky. See:

如果您的 JSON 太大而json_decode()无法立即处理,事情就会开始变得棘手。看:



How to sort it

如何排序

See: Reference: all basic ways to sort arrays and data in PHP.

请参阅:参考:在 PHP 中对数组和数据进行排序的所有基本方法

回答by Mohd Abdul Mujib

You can use json_decode()to convert a json string to a PHP object/array.

您可以使用json_decode()将 json 字符串转换为 PHP 对象/数组。

Eg.

例如。

Input:

输入:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

Output:

输出:

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

Few Points to remember:

需要记住的几点:

  • json_decoderequires the string to be a valid jsonelse it will return NULL.
  • In the event of a failure to decode, json_last_error()can be used to determine the exact nature of the error.
  • Make sure you pass in utf8content, or json_decodemay error out and just return a NULLvalue.
  • json_decode要求字符串是有效的,json否则它将返回NULL
  • 在解码失败的情况下,json_last_error()可用于确定错误的确切性质。
  • 确保您传入utf8内容,否则json_decode可能会出错并只返回一个NULL值。

回答by Sayeed amin

// Using json as php array 

$json = '[{"user_id":"1","user_name":"Sayeed Amin","time":"2019-11-06 13:21:26"}]';

//or use from file
//$json = file_get_contents('results.json');

$someArray = json_decode($json, true);

foreach ($someArray as $key => $value) {
    echo $value["user_id"] . ", " . $value["user_name"] . ", " . $value["time"] . "<br>";
}

回答by Kankatala Krishna

We can decode json string into array using json_decode function in php

我们可以使用 php 中的 json_decode 函数将 json 字符串解码为数组

1) json_decode($json_string) // it returns object

1) json_decode($json_string) // 返回对象

2) json_decode($json_string,true) // it returns array

2) json_decode($json_string,true) // 返回数组

$json_string = '{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';
$array = json_decode($json_string,true);

echo $array['type']; //it gives donut

回答by Paul Burilichev

Consider using JSONPathhttps://packagist.org/packages/flow/jsonpath

考虑使用JSONPathhttps://packagist.org/packages/flow/jsonpath

There is a pretty clear explanation of how to use it and parse a JSON-file avoiding all the loopsproposed. If you are familiar with XPathfor XMLyou will start loving this approach.

关于如何使用它并解析 JSON 文件以避免所有建议的循环,有一个非常清楚的解释。如果你熟悉XPathforXML你就会开始喜欢这种方法。

回答by MAChitgarha

I have written a package named JSON(GitHub, Packagist). If you want to prevent overheads of using json_*functions, you should try it.

我写了一个名为JSONGitHubPackagist)的包。如果你想防止使用json_*函数的开销,你应该尝试一下。

Example

例子

use MAChitgarha\Component\JSON;

$jsonStr = <<<JSON
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}
JSON;

// Create an instance
$json = new JSON($jsonStr);

// Get a nested element using dots
$json->get("toppings.1.type"); // Chocolate with Sprinkles
$json["toppings.1.type"]; // Chocolate with Sprinkles

// Iterate over an element
foreach ($json->iterate("toppings") as $item)
    echo "{$item->id}: {$item->type}", PHP_EOL;

// Change an element
$json->set("toppings.3", [
    "id" => "5000",
    "type" => "Unknown"
]);

// Get data as JSON string, array or object, respectively
$json->getDataAsJson();
$json->getDataAsArray();
$json->getDataAsObject();

See the wiki, or the quick tutorialto get familiar with it.

请参阅wiki快速教程以熟悉它。

Furthermore, if you want to read JSON files and extract its data (as it seems you're trying to perform this), see JSONFilepackage, which I have written it, too.

此外,如果您想读取 JSON 文件并提取其数据(因为您似乎正在尝试执行此操作),请参阅我也编写的JSONFile包。

回答by harish sharma

https://paiza.io/projects/X1QjjBkA8mDo6oVh-J_63w

https://paiza.io/projects/X1QjjBkA8mDo6oVh-J_63w

Check below code for converting json to array in PHP, If JSON is correct then json_decode()works well, and will return an array, But if malformed JSON, then It will return NULL,

检查下面将 json 转换为数组的代码PHP,如果 JSON 正确则json_decode()运行良好,并将返回一个数组,但如果 JSON 格式错误,则它将返回NULL

<?php
function jsonDecode1($json){
    $arr = json_decode($json, true);
    return $arr;
}

// In case of malformed JSON, it will return NULL
var_dump( jsonDecode1($json) );

If malformed JSON, and you are expecting only array, then you can use this function,

如果 JSON 格式错误,并且您只需要数组,那么您可以使用此函数,

<?php
function jsonDecode2($json){
    $arr = (array) json_decode($json, true);
    return $arr;
}

// In case of malformed JSON, it will return an empty array()
var_dump( jsonDecode2($json) );

If malformed JSON, and you want to stop code execution, then you can use this function,

如果 JSON 格式错误,并且您想停止代码执行,那么您可以使用此功能,

<?php
function jsonDecode3($json){
    $arr = (array) json_decode($json, true);

    if(empty(json_last_error())){
        return $arr;
    }
    else{
        throw new ErrorException( json_last_error_msg() );
    }
}

// In case of malformed JSON, Fatal error will be generated
var_dump( jsonDecode3($json) );

You can use any function depends on your requirement,

您可以使用任何功能取决于您的要求,