在浏览器控制台或Javascript中打印或显示PHP数组

时间:2017-02-19 07:50:57

标签: javascript php arrays

我需要使用javascript在浏览器控制台中打印php数组

这里我分享了我的代码

<?php
function browser_console($data) {
    echo "<script>console.log('" . $data . "');</script>";
}

如果有人知道最佳代码,请告诉我。

谢谢

4 个答案:

答案 0 :(得分:13)

尝试使用json_encode()

实施例

echo "<script>console.log('" . json_encode($data) . "');</script>";

答案 1 :(得分:3)

我正在使用

echo "<script>console.log(".json_encode(var_export($object, true)).");</script>";

因为它允许您显示复杂的PHP对象,而不仅仅是数组。

答案 2 :(得分:2)

您可以使用json_encode在json中解析数组,并能够从javascript中读取它:

PHP文件:

<?php 

$data = array(
    "data" => "Hello",
    "data1" => "World"
);

echo "<script>console.log(".json_encode($data).");</script>";

Web控制台中的输出:

  

对象{数据:“你好”,数据1:“世界”}

答案 3 :(得分:0)

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.