1

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:

JSFiddle Demo

1

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Wow!! You're fast :-D var data = [["McDonalds","Fast Food","London"],["Marios","Italian","Manchester"]]; document.write(data); is my new output - it worked beautifully :-)
Have to wait 6 minutes before accepting your answer. Thank you :-)
1

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>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.