I have a PHP variable which contains a JSON
object in string format.
<?php
$url = "http://ip-api.com/json";
$phpObj = file_get_contents($url);
?>
Javascript:
<script>
var obj = "<?php echo $phpObj; ?>";
</script>
When I try to echo a PHP variable in javascript
, I get the following error:
Uncaught SyntaxError: Invalid or unexpected token.
I've tried using json_encode
, but it gives me the same error.
No need to use the quotes ("
s) and json_encode
as it is already a JSON object. Try
var obj = <?php echo $phpObj; ?>;
When I ma fetching the data and try -
<?php
$phpObj = file_get_contents("http://ip-api.com/json");
?>
<script>
var obj = <?php echo $phpObj; ?>;
console.log(obj);
</script>
I am getting -
{as: "AS45194 Syscon Infoway Pvt. Ltd.", city: "Thane", country: "India", countryCode: "IN", isp: "Syscon Infoway Pvt.", …}
in the console.
Passing simple arrays or arrays of objects between PHP and JavaScript can be done through json_encode
and json_decode
respectively. For instance, in your case, I can do the following
<?php
$url = "http://ip-api.com/json";
$phpObj = file_get_contents($url);
?>
<script>
var obj = <?php echo $phpObj; ?>;
</script>
Since the data fetched is JSON.
However, this fully depends on your application. If $phpObj = file_get_contents($url);
returns json then I will simply do the following
<script>
var obj = <?php echo $phpObj; ?>;
</script>
If it's an object that is returned($phpObj
), then I will, first of all, convert the object to an array then parse it into JSON format then echo it to JavaScript as shown below
<script>
var obj = <?php echo json_encode((array)$phpObj); ?>;
</script>
If it's an array that is returned, then I will parse the variable to JSON format then echo it to JavaScript as shown below
<script>
var obj = <?php echo json_encode($phpObj); ?>;
</script>
For the case of json_decode
, if for instance, you want to use the value returned by file_get_contents($url);
and assuming this returns JSON, you can convert the JSON to a PHP array or a PHP object as shown below,
$data_obj = json_decode($phpObj); //Return object not array
$data_arr = json_decode($phpObj,true); //Return array not object