What are the best practices for formatting and outputting JSON data in PHP to ensure compatibility with JavaScript for frontend display?

When formatting and outputting JSON data in PHP for frontend display, it is important to ensure that the data is properly encoded and formatted to be compatible with JavaScript. To achieve this, use the json_encode() function in PHP to convert your data into a JSON string. Additionally, set the appropriate headers in your PHP script to indicate that the content being returned is JSON.

<?php
// Sample data to be encoded as JSON
$data = array(
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'johndoe@example.com'
);

// Encode the data as JSON
$jsonData = json_encode($data);

// Set the appropriate headers
header('Content-Type: application/json');

// Output the JSON data
echo $jsonData;
?>