11

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

4
  • not on click ... when page loads it should print..
    – Kavin D
    Feb 19, 2017 at 8:05
  • 1
    You should state the problem clearly - I assume in this case you simply could not get it to work and saw nothing.
    – yakobom
    Feb 19, 2017 at 8:57
  • Who is executing browser_console? Feb 19, 2017 at 9:12
  • i got it , thank you guys...
    – Kavin D
    Feb 19, 2017 at 9:45

4 Answers 4

35

Try using json_encode()

Example

echo "<script>console.log('" . json_encode($data) . "');</script>";
1
  • 1
    Be carefull, you pass the $data array as string.
    – JazZ
    Feb 19, 2017 at 8:12
11

Try adding JSON.parse in addition to what the others said - that way it gets console.logged 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>";

screenshot of expanded object echoed like above

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.

10

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.

1
  • This is the only answer that worked for me. Jun 28, 2021 at 0:31
2

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" }

1
  • @Kavin. Glad to hear it but this solution is different. Here you can use the json object from javascript. In the accepted solution, the json object is passed to javascript as a string.
    – JazZ
    Feb 19, 2017 at 8:15

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.