How can JSON or JSONP be used to return variable contents from a PHP file to JavaScript?

To return variable contents from a PHP file to JavaScript, you can use JSON or JSONP. JSON is a lightweight data-interchange format that is easy for humans to read and write, while JSONP is a method for sending JSON data without being restricted by the same-origin policy. You can encode your PHP variables into JSON format and then output them in your PHP file, which can be easily accessed and parsed in JavaScript.

<?php
// PHP file to return variable contents in JSON format
$variable1 = "Hello";
$variable2 = "World";

$data = array(
    'variable1' => $variable1,
    'variable2' => $variable2
);

header('Content-Type: application/json');
echo json_encode($data);
?>