I'd like to populate my data array with the contents of a CSV file using PHP.
My current code:
<script src="http://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
<?php
$file = fopen('food.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
print_r($line);
}
fclose($file);
?>
<script type="text/javascript">
var data = <?php echo json_encode($line); ?>;
document.write(data);
</script>
However, when I run this, I get the following output:
Array
(
[0] => McDonalds
[1] => Fast Food
[2] => London
)
Array
(
[0] => Marios
[1] => Italian
[2] => Manchester
)
<script type="text/javascript">
var data = false;
document.write(data);
</script>
I'm guessing the $line variable is my issue here.
My food.csv file:
McDonalds,Fast Food,London
Marios,Italian,Manchester
The plan is to incorporate the data array into something like the demo below:
worldofjr
3,9068 gold badges41 silver badges53 bronze badges
asked Oct 11, 2016 at 12:43
michaelmcgurk
6,54525 gold badges102 silver badges197 bronze badges
2 Answers 2
each time you print a line you override the previous one. Also you're using jsonencode with a nonarray I think thats why it gives you false, try this:
$file = fopen('food.csv', 'r');
$allfile = [];
while (($line = fgetcsv($file)) !== FALSE) {
print_r($line);
$allfile[] = $line;
}
fclose($file);
?>
<script type="text/javascript">
var data = <?php echo json_encode($allfile); ?>;
document.write(data);
</script>
answered Oct 11, 2016 at 12:50
Aschab
1,3992 gold badges15 silver badges32 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
michaelmcgurk
Wow!! You're fast :-D
var data = [["McDonalds","Fast Food","London"],["Marios","Italian","Manchester"]]; document.write(data); is my new output - it worked beautifully :-)michaelmcgurk
Have to wait 6 minutes before accepting your answer. Thank you :-)
Instead of using print_r() save each line into an array and json_encode that. For example;
<?php
$arr = [];
$file = fopen('food.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
$arr[] = $line;
}
fclose($file);
?>
<script type="text/javascript">
var data = <?php echo json_encode($arr); ?>;
document.write(data);
</script>
answered Oct 11, 2016 at 12:51
worldofjr
3,9068 gold badges41 silver badges53 bronze badges
Comments
default
JavaScript Object Notationformat.