What are some common pitfalls when decoding and outputting JSON data in PHP?

One common pitfall when decoding and outputting JSON data in PHP is not properly handling errors that may occur during the decoding process, such as invalid JSON syntax. To solve this issue, you should wrap the decoding process in a try-catch block and handle any potential exceptions that may be thrown.

$jsonData = '{"name": "John", "age": 30}';
try {
    $decodedData = json_decode($jsonData);
    if ($decodedData === null && json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Error decoding JSON data');
    }
    echo json_encode($decodedData);
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}