Import php array into javascript dataset

时间:2015-05-24 21:46:25

标签: javascript php html arrays

I have extracted some data and organized them in an array in .php file.

Now I want to visualize that data using d3 methods in another file with .html extension. I would like to import that array into the dataset.

I'll try to post the code or what makes sense here:

<?php

        // data extraction from a bunch of xml files.
        // stored all of that in an array ---- $topics 
        // sorted the array by frequency of the elements 

        $topic_count = array_count_values($topics);

        echo '<p>' . "Array Testing " . '</p>';

        foreach ($newArray as $key => $value) {
                echo "$key - <strong>$value</strong> <br />"; 
        }

    ?>

The output from the foreach is:

tim harper published - 5
TIM HARPER Published - 3
Updated - 1
Illustration Garnotte - 1
cour rejette - 1
cour supr me rejette les peines obligatoires du gouvernement harper - 1
Chris Wattie - 1
Stephen Harper - 1
contenu publication - 1
information - 1
juif canadien - 1

When I do echo json_encode($newArray,JSON_PRETTY_PRINT); the output is:

{
    "tim harper published": 5,
    "TIM HARPER Published": 3,
    "Updated": 1,
    "Illustration Garnotte": 1,
    "cour rejette": 1,
    "cour supr me rejette les peines minimales obligatoires du gouvernement harper": 1,
    "Chris Wattie": 1,
    "Stephen Harper": 1,
    "contenu publication": 1,
    "information": 1,
    "juif canadien": 1
}

I have tried doing:

script type = "javascript">
            var dataset = <?php echo json_encode($newArray,JSON_PRETTY_PRINT); ?>;
        </script>

but I can't get the data to use.

Seems like I'm getting out of topic here, but my question is how can I import that data in my html file. (same folder ofcourse)

1 个答案:

答案 0 :(得分:4)

You can save the data in a text file and parse it.

var jsonphp = '<?php echo $d = file_get_contents("json.txt"); ?>';
var jsondata = $.parseJSON(jsonphp);