What are the advantages of returning database results as JSON or XML in PHP?

Returning database results as JSON or XML in PHP allows for easy parsing and manipulation of the data in frontend applications. JSON and XML are widely supported data formats that can be easily consumed by various programming languages and platforms. This approach also helps in separating the data layer from the presentation layer, making the code more modular and maintainable.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare and execute a SQL query
$stmt = $pdo->query('SELECT * FROM my_table');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Return results as JSON
header('Content-Type: application/json');
echo json_encode($results);