May 3, 2012
Basic JSON With PHP
Question by Talon
I have some Data like this in PHP:
NumberOfPeople.php
<?php
$numberOfPeople = 5;
?>
How do I convert that variable into a JSON Object and then output it into an HTML file.
Something like this:
RandomHTMLFile.html
<script type="text/javascript">
var NumberOfPeople = JSON VARIABLE FROM THE PHP FILE
</script>
This is the type of thing JSON is for right?
Notice that the Output file is in an HTML file and not a PHP File, so it has to be completely Javascript based.
Also the HTML file will be on a different server than the PHP file.
Answer by Starx
Change it into a PHP array and use json_encode()
function
$jsonArray = array('numberOfPeople' => 5); //Now the value will be accessible under `numberOfPeople` json index
$json = json_encode($jsonArray);
echo $json;