How can PHP be used to send data as an API to JavaScript in the front-end?
To send data as an API from PHP to JavaScript in the front-end, you can use PHP to create an endpoint that outputs data in JSON format. This data can then be fetched by JavaScript using an AJAX request. By encoding the data in JSON format, it can be easily parsed and used in the front-end application.
<?php
// Sample PHP code to send data as an API to JavaScript
// Data to be sent
$data = array(
'name' => 'John Doe',
'age' => 30,
'city' => 'New York'
);
// Set header to indicate JSON response
header('Content-Type: application/json');
// Output data in JSON format
echo json_encode($data);
?>