Home > Backend Development > PHP Tutorial > Application of PHP functions in JSON processing

Application of PHP functions in JSON processing

WBOY
Release: 2024-04-15 16:54:01
Original
959 people have browsed it

There are two main functions used to process JSON data in PHP: json_encode() is used to encode PHP data into a JSON string. json_decode() is used to decode a JSON string into a PHP data structure.

PHP 函数在 JSON 处理中的应用

Application of PHP functions in JSON processing

JSON (JavaScript Object Notation) is a method used in servers and Web A lightweight data format for exchanging data between applications. PHP provides various functions to process JSON data.

Encoding JSON data

To encode the PHP data structure into a JSON string, you can use the json_encode() function:

$data = [
    'name' => 'John Doe',
    'age' => 30
];

$json = json_encode($data);
Copy after login

Decoding JSON data

To decode a JSON string into a PHP data structure you can use json_decode() Function:

$json = '{"name":"John Doe","age":30}';

$data = json_decode($json, true);
Copy after login

Note: true Parameters decode the JSON object into an array. To decode a JSON string into an object, replace the true parameter with false.

Practical case

Use AJAX to obtain JSON data:

// ajax_data.php
$data = [
    'name' => 'John Doe',
    'age' => 30
];

echo json_encode($data);
Copy after login
// main.js
fetch('ajax_data.php')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });
Copy after login

Use JSON to validate the form data:

if (isset($_POST['submit'])) {
    $data = json_decode(file_get_contents('php://input'), true);

    // 验证数据 ...
}
Copy after login

Other useful JSON functions

  • json_last_error(): Get the error code of the last JSON operation.
  • json_last_error_msg(): Get the error description of the last JSON operation.
  • json_pretty_print(): Format JSON output into human-readable form.

The above is the detailed content of Application of PHP functions in JSON processing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template