首頁  >  文章  >  後端開發  >  如何在 PHP 中處理 JSON 請求?

如何在 PHP 中處理 JSON 請求?

Patricia Arquette
Patricia Arquette原創
2024-10-20 23:01:29275瀏覽

How to Handle JSON Requests in PHP?

在 PHP 中處理 JSON 請求

在 AJAX 請求中提交資料時,contentType 標頭指定要傳送的資料的格式。預設的 x-www-form-urlencoded 編碼將資料編碼為鍵值對,而 application/json 將其編碼為 JSON 字串。

當 contentType 設定為 application/json 時,PHP 內建的 $_POST會儲存表單參數的變數變成空。這是因為原始 JSON 字串不會自動解析為單獨的參數。

要在 PHP 中正確處理 JSON 請求,請使用以下程式碼:

<code class="php"><?php
var_dump(json_decode(file_get_contents('php://input')));
?></code>

file_get_contents('php:// input') 讀取原始請求正文。然後 json_decode() 將 JSON 字串解析為 PHP 物件或數組,可以像其他 PHP 變數一樣存取它。

這是一個範例用法:

<code class="php">// Assume an incoming request with the following JSON body:
{
  "my_params": 123
}

// Parse the JSON request
$data = json_decode(file_get_contents('php://input'));

// Access the parsed data like any other PHP variable
$my_params = $data->my_params;</code>

以上是如何在 PHP 中處理 JSON 請求?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn