首頁 後端開發 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 Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1665
14
CakePHP 教程
1424
52
Laravel 教程
1321
25
PHP教程
1269
29
C# 教程
1249
24
說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? 說明PHP中的安全密碼散列(例如,password_hash,password_verify)。為什麼不使用MD5或SHA1? Apr 17, 2025 am 12:06 AM

在PHP中,應使用password_hash和password_verify函數實現安全的密碼哈希處理,不應使用MD5或SHA1。1)password_hash生成包含鹽值的哈希,增強安全性。 2)password_verify驗證密碼,通過比較哈希值確保安全。 3)MD5和SHA1易受攻擊且缺乏鹽值,不適合現代密碼安全。

PHP和Python:比較兩種流行的編程語言 PHP和Python:比較兩種流行的編程語言 Apr 14, 2025 am 12:13 AM

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP行動:現實世界中的示例和應用程序 PHP行動:現實世界中的示例和應用程序 Apr 14, 2025 am 12:19 AM

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP:網絡開發的關鍵語言 PHP:網絡開發的關鍵語言 Apr 13, 2025 am 12:08 AM

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP的持久相關性:它還活著嗎? PHP的持久相關性:它還活著嗎? Apr 14, 2025 am 12:12 AM

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? PHP類型提示如何起作用,包括標量類型,返回類型,聯合類型和無效類型? Apr 17, 2025 am 12:25 AM

PHP類型提示提升代碼質量和可讀性。 1)標量類型提示:自PHP7.0起,允許在函數參數中指定基本數據類型,如int、float等。 2)返回類型提示:確保函數返回值類型的一致性。 3)聯合類型提示:自PHP8.0起,允許在函數參數或返回值中指定多個類型。 4)可空類型提示:允許包含null值,處理可能返回空值的函數。

PHP和Python:代碼示例和比較 PHP和Python:代碼示例和比較 Apr 15, 2025 am 12:07 AM

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

PHP與其他語言:比較 PHP與其他語言:比較 Apr 13, 2025 am 12:19 AM

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

See all articles