ตัวอย่าง php header json

Here’s an example of a PHP header for sending data in JSON format:

PHP

<?php
// Set the content type header to application/json
header("Content-Type: application/json; charset=UTF-8");

// Your data to be encoded in JSON format
$data = array(
  "message" => "Hello, world!",
  "data" => array(
    "name" => "John Doe",
    "age" => 30
  )
);

// Encode the data to JSON string
$json_data = json_encode($data);

// Echo the JSON data
echo $json_data;
?>

Explanation:

  1. header Function: The header function is used to send HTTP headers to the browser. In this case, we’re setting the Content-Type header to application/json. This tells the browser that the following data is in JSON format.
  2. charset=UTF-8: Specifying charset=UTF-8 ensures proper encoding of characters, especially if your data contains characters outside the basic ASCII range.
  3. Data to Encode: The $data variable holds the information you want to send as JSON. It can be an array of key-value pairs, a single object, or any other data structure that can be encoded by json_encode.
  4. json_encode Function: This function converts the PHP data structure ($data) into a JSON string.
  5. echo Statement: Finally, the echo statement sends the JSON string ($json_data) to the browser.

Running the Script:

Save this code as a PHP file (e.g., json_example.php) and run it on your server. When you access the script in your browser, it should display the JSON data:

JSON

{"message":"Hello, world!","data":{"name":"John Doe","age":30}}

This demonstrates a basic example of sending JSON data from a PHP script. You can modify the data structure and logic according to your specific needs.

Related Posts
 jquery vslidation remove spaces from input คืออะไร

jQuery validation remove spaces from input คือ ฟังก์ชันที่ใช้ลบช่องว่างออกจาก input field โดยใช้ jQuery วิธีใช้ JavaScri Read more

dimiss keyboard flutter คืออะไร

ใน Flutter dismiss keyboard หมายถึง การซ่อนแป้นพิมพ์เสมือนบนหน้าจอ วิธีการ dismiss keyboard ใช้ FocusNode: Dart imp Read more

bootstrap5 cdn คืออะไร

Bootstrap5 CDN คือ Content Delivery Network ของ Bootstrap 5 ซึ่งเป็นเฟรมเวิร์ก front-end ยอดนิยมที่ช่วยให้นักพัฒนาเว็บสร Read more

เขียนโค้ดดึงเนื้อหาจาก wordpress

โค้ดดึงเนื้อหาจาก WordPress วิธีดึงเนื้อหาจาก WordPress มีหลายวิธี ขึ้นอยู่กับประเภทของเนื้อหาที่ต้องการดึง ดึงบทความทั้ Read more