What are the best practices for formatting and encoding JSON data in PHP for web services?

When formatting and encoding JSON data in PHP for web services, it is important to ensure that the data is properly structured and encoded to prevent any parsing errors on the client side. To achieve this, you can use the json_encode() function in PHP to convert an array or object into a JSON string. Additionally, it is recommended to set the appropriate headers to indicate that the response is in JSON format.

// Sample PHP code for formatting and encoding JSON data for web services

// Sample data to be encoded into JSON
$data = array(
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'john.doe@example.com'
);

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

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

// Output the JSON data
echo $jsonData;