i need to print php array in browser console using javascript
here i shared my code
<?php
function browser_console($data) {
echo "<script>console.log('" . $data . "');</script>";
}
if anybody knows best code let me know .
thank you
i need to print php array in browser console using javascript
here i shared my code
<?php
function browser_console($data) {
echo "<script>console.log('" . $data . "');</script>";
}
if anybody knows best code let me know .
thank you
Try using json_encode()
Example
echo "<script>console.log('" . json_encode($data) . "');</script>";
Try adding JSON.parse in addition to what the others said - that way it gets console.log
ged as an object, meaning you can expand it and navigate it in Chrome like so.
echo "<script>console.log(JSON.parse('" . json_encode($data) . "'));</script>";
Source: https://alligator.io/js/json-parse-stringify/
Note: I understand this question is asking about arrays, so string is probably fine, but to represent more complex objects this works better.
I'm using
echo "<script>console.log(".json_encode(var_export($object, true)).");</script>";
as it allows you to display complex PHP objects and not only up to arrays.
You could use json_encode
to parse the array in json and be able to read it from javascript :
PHP file :
<?php
$data = array(
"data" => "Hello",
"data1" => "World"
);
echo "<script>console.log(".json_encode($data).");</script>";
Output in Web Console :
Object { data: "Hello", data1: "World" }