14

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.. Commented 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. Commented Feb 19, 2017 at 8:57
  • Who is executing browser_console? Commented Feb 19, 2017 at 9:12
  • i got it , thank you guys... Commented Feb 19, 2017 at 9:45

4 Answers 4

40

Try using json_encode()

Example

echo "<script>console.log('" . json_encode($data) . "');</script>";
Sign up to request clarification or add additional context in comments.

1 Comment

Be carefull, you pass the $data array as string.
12

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.

Comments

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 Comment

This is the only answer that worked for me.
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 Comment

@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.