简体   繁体   中英

pass php array to json file (PHP ->Json->JS)

I have php code

<?php
$csv = array_map('str_getcsv', file('/web2016-master/projectclass/data/file.csv'));
array_walk($csv, function(&$a) use ($csv) {
    $a = array_combine($csv[0], $a);
});
array_shift($csv); # remove column header
json_encode($csv);
?>

I have a json file where I wont to pass the json_encode($csv) ;

and I have javascript that uses json file

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    var file = JSON.parse(xhr.responseText);
    var statusHTML = '<tr>';

    for (var i = 0; i < file.length; i += 1) {
      statusHTML += '<td>';
      statusHTML += file[i].FirstName;
      statusHTML += '</td>';
      statusHTML += '<td>';
      statusHTML += file[i].LastName;
      statusHTML += '</td>';
      statusHTML += '<td>';
      statusHTML += '<a href="#">advise</a>';
      statusHTML += '</td>';
      statusHTML += '</tr>';
    }
    document.getElementById('studentList').innerHTML = statusHTML;
  }
};
xhr.open('GET', 'data/file.json');
xhr.send();

What do I need to include in json file so that PHP->Json->JS.

check out file_put_contents

<?php
$csv = array_map('str_getcsv', file('/web2016-master/projectclass/data/file.csv'));
array_walk($csv, function(&$a) use ($csv) {
    $a = array_combine($csv[0], $a);
});
array_shift($csv); # remove column header
file_put_contents('data/file.json', json_encode($csv));
?>

You could also echo the content and consume the output, though that would require you parsing the file each request (unless you put some caching in place):

<?php
$csv = array_map('str_getcsv', file('/web2016-master/projectclass/data/file.csv'));
array_walk($csv, function(&$a) use ($csv) {
    $a = array_combine($csv[0], $a);
});
array_shift($csv); # remove column header
header('Content-Type: application/json');
echo json_encode($csv);
?>

And have your javascript request your PHP file:

xhr.open('GET', 'yourfile.php');

You need to call the PHP file. Javascript makes an ajax call to PHP which returns JSON. There's no need for an intermediate json file unless you have additional requirements not mentioned in the question.

xhr.open('GET', 'data/file.php');

You may need to cleanup the javascript logic a bit, take a look at this post for an example of making ajax calls without jQuery. How to make an AJAX call without jQuery?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM