백엔드 개발 PHP 튜토리얼 How To Parse JSON With PHP

How To Parse JSON With PHP

Jun 23, 2016 pm 02:31 PM

Parsing a JSON file or string is just as easy as parsing XML once you get the syntax, and in this tutorial I’ll show you how to parse and learn its syntax. But before we begin let’s establish some naming conventions for PHP arrays just in case you don’t know them already.




Take a look at the following PHP array.

$arrayName[key]=value;
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

Arrays in PHP have three parts, the name or variable used, the key ( can be associative or numeric) and the value of that key.

When we read/parse a json string or file with PHP what we will be doing is basically assigning a bunch of keys to a variable and so that variable will become an associative array. In case you haven’t heard the terms associative or numeric, numeric simply means that you are using numbers as keys.

Now that we got a convention let’s look at a simple JSON string.

$string='{"name":"John Adams"}';
로그인 후 복사

You can think of this string as a key “name” that holds the value “John Adams”. Notice the brackets, they are used to separate arrays of keys. So we can give the following naming convention to this json string

{"key":"value"}
로그인 후 복사

To parse JSON with PHP we will be using the funcion json_decode , this function takes a json string for its first parameter and an optional boolean (true/false) for its second parameter. The second parameter, if set to true, returns the json string as an associative array, if it’s not set it will return an object. The main difference between the two options is the syntax you use to refer to keys, for now we’ll be setting the second parameter to true so that it returns the more familiar associative array, but we will cover objects.

Now that you know about this new function make your php file look like mine.

$string='{"name":"John Adams"}';$json_a=json_decode($string,true);
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

Using json_decode with the second parameter set to true we have assigned an associative array to the variable $json_a, so $json_a is now an array. I use “_a” to refer to an associative array, we’ll later use $json_o to refer to a variable that holds the json as an object but you can use whatever variable name you want.

Let me translate the code above to a more familar and basic snippet that is doing the same thing.

$json_a=array("name"=>"John Adams");// or also$json_a["name"]="John Adams";
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

Now it’s clear what you can do with “$json_a” right? To show contents of “name” you would simply echo $json_a[name] like this

echo $json_a[name];// and you should see the name John Adams printed on your browser.
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

That was easy, now let’s use the same json string but this time we won’t set the second parameter so that we can get an object. Fill your php file with the following code.

$string='{"name":"John Adams"}';$json_o=json_decode($string);
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

This time instead of returning an array, json_decode has returned an object. The word object might sound a little intimidating but believe me when I say this isn’t hard at all.

To show the contents of “name” all one has to do is this

echo $json_o->name;
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

Can you tell the difference between outputting $json_a and $json_o’s content? That’s right! the only difference is that with $json_o you get rid of the leading “]” and replace “[” with “->”.

echo $json_a[name];// andecho $json_o->name;// will both display “John Adams”
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

The json string we've been using is very simple so am going to make it a little more interesting. The content of your php file up to this point should be this

$string='{"name":"John Adams"}';// create object from string$json_o=json_decode($string);// create array from string$json_a=json_decode($string,true);
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

Whenever I make changes to the value of your $string variable keep the last two lines with json_decode for the rest of this tutorial.

$string='{                     "name":"John Adams",                     "age":"40"                   }';$json_o=json_decode($string);$json_a=json_decode($string,true);
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

As you might guess from the the new way $string looks, you separate each set of keys and values with a comma. So to display to value of age, which is 40, you can use either of these two methods.

// associative array modeecho $json_a[age];// object modeecho $json_o->age;
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

But this JSON string is still too simple, why don't we assign two keys to a key. Then new json string will be this.

$string='{                     "name":{"first":"John","last":"Adams"},                     "age":"40"                   }';
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

What we’ve done is we have separated the name “John Adams” into two "subkeys;” , first and last. We can display the values of these new keys this way.

// array method  // display first name echo  $json_a[name][first];  // display last name echo  $json_a[name][last];// object method  // display first name  echo $json_o->name->first;  // display last name  echo $json_o->name->last;
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

So far so good. You have probably seen the symbols [ and ] used in json and if you haven't you will right now because that's what our new $string variable will include.

$string='[            {                "name":{"first":"John","last":"Adams"},                                "age":"40"            },            {                "name":{"first":"Thomas","last":"Jefferson"},                                "age":"35"            }         ]';
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

We use [ and ] to indicate that we have an array of keys, that is more than one set of { }'s. That means then, that this string has two arrays , each of them separated by { and } and followed by a comma except for the last one. This array is numeric, so to access "age" in the second array we'll do the following.

// remember that arrays start at zero, that's why we use 1 to refer to the second array// array methodecho $json_a[1][age];// object methodecho $json_o[1]->age;
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

In your web development career you will encounter yet another type of json string.

$string='{"person":         [            {                "name":{"first":"John","last":"Adams"},                "age":"40"            },            {                "name":{"first":"Thomas","last":"Jefferson"},                "age":"35"            }         ]         }';
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

This string is just like the previous one except that we have added {"person": at the beginning and to close, we added a } at the end.

What we have here is two "person" arrays one for John and one for Thomas. You can display both last names with this snippet of code.

// array method     // first person "0"echo $json_a[person][0][name][last];    // second person "1"echo $json_a[person][1][name][last];// object method   // first person "0"echo $json_o->person[0]->name->last;  // second person "1"echo $json_o->person[1]->name->last;
로그인 후 복사

로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사
로그인 후 복사

It all seems fine, until we have a 100 "person" array or more! But don't worry. Because these arrays are numeric we can use a loop to go through a huge array like that. I like to use "foreach" loops but you can use "while", "for" or "do while" loops if you want. The next snippet will show you how you can get each person's information using a foreach loop.

$string='{"person":[            {                "name":{"first":"John","last":"Adams"},                "age":"40"            },            {                "name":{"first":"Thomas","last":"Jefferson"},                "age":"35"            }         ]}';$json_a=json_decode($string,true);$json_o=json_decode($string);// array methodforeach($json_a[person] as $p){echo 'Name: '.$p[name][first].' '.$p[name][last].'Age: '.$p[age].'';}// object methodforeach($json_o->person as $p){echo 'Name: '.$p->name->first.' '.$p->name->last.'Age: '.$p->age.'';}
로그인 후 복사

Reading a JSON is just as easy and it does not have a special extension, the file just has to output a json string. To read a JSON file you can use the function file_get_contents like this $string=file_get_contents(filepath) . Now pass $string to json_decode and parse.

From:http://webhole.net/2009/08/31/how-to-read-json-data-with-php/

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Laravel의 플래시 세션 데이터로 작업합니다 Laravel의 플래시 세션 데이터로 작업합니다 Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Mar 13, 2025 pm 12:08 PM

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

PHP에서 늦은 정적 결합의 개념을 설명하십시오. PHP에서 늦은 정적 결합의 개념을 설명하십시오. Mar 21, 2025 pm 01:33 PM

기사는 PHP 5.3에 도입 된 PHP의 LSB (Late STATIC BING)에 대해 논의하여 정적 방법의 런타임 해상도가보다 유연한 상속을 요구할 수있게한다. LSB의 실제 응용 프로그램 및 잠재적 성능

프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. 프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. Mar 28, 2025 pm 05:12 PM

이 기사에서는 프레임 워크에 사용자 정의 기능 추가, 아키텍처 이해, 확장 지점 식별 및 통합 및 디버깅을위한 모범 사례에 중점을 둡니다.

프레임 워크 보안 기능 : 취약점 보호. 프레임 워크 보안 기능 : 취약점 보호. Mar 28, 2025 pm 05:11 PM

기사는 입력 유효성 검사, 인증 및 정기 업데이트를 포함한 취약점을 방지하기 위해 프레임 워크의 필수 보안 기능을 논의합니다.

See all articles