简体   繁体   English

将php数组传递到json文件(PHP-> Json-> JS)

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

I have php code 我有php代码

<?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) ; 我有一个json文件,我不会在其中传递json_encode($csv)

and I have javascript that uses json file 而且我有使用json文件的JavaScript

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. 我需要在json文件中包含什么,以便PHP-> Json-> JS。

check out file_put_contents 检出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: 并让您的JavaScript请求您的PHP文件:

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

You need to call the PHP file. 您需要调用PHP文件。 Javascript makes an ajax call to PHP which returns JSON. Javascript对PHP进行ajax调用,该调用返回JSON。 There's no need for an intermediate json file unless you have additional requirements not mentioned in the question. 除非您有问题中未提到的其他要求,否则不需要中间的json文件。

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. 您可能需要稍微清理一下javascript逻辑,请看一下这篇文章,以获取不使用jQuery进行ajax调用的示例。 How to make an AJAX call without jQuery? 如何在没有jQuery的情况下进行AJAX调用?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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