简体   繁体   English

将CSV文件读入JavaScript字符串或数组

[英]Reading CSV file into javascript string or array

I'm having a very specific problem so I hope someone can help. 我遇到了一个非常具体的问题,因此希望有人可以提供帮助。 I'm building a map app with a CakePHP backend framework. 我正在使用CakePHP后端框架构建地图应用程序。 I'm currently attempting to import some data into my application for manipulation, I have a google docs CSV file (i also have a local version) and I'm also using an custom js library. 我目前正在尝试将一些数据导入到我的应用程序中进行操作,我有一个google docs CSV文件(我也有一个本地版本),并且我还在使用自定义js库。 So i have a declaration that goes like so: 所以我有一个这样的声明:

mapbox.markers.layer().csv('csvstring');

csvstring equates to a standard string of CSV data, i looked at some examples on the mapbox website but all had hardcoded data, eg csvstring = 'lat,lon\\n,0,0'; csvstring等同于标准CSV数据字符串,我在mapbox网站上查看了一些示例,但所有示例均具有硬编码数据,例如csvstring = 'lat,lon\\n,0,0';

Is there a simple way to read either the google doc, or read the file from my CakePHP directory, into a string variable or, failing that, an array? 是否有一种简单的方法可以读取google doc,或从CakePHP目录中读取文件,将其读取到字符串变量中,否则,将其读取到数组中? I've scoured the internet for days and haven't been able to find a solution. 我已经搜寻互联网好几天了,却找不到解决方案。 If its possible to let PHP do the dirty work and then pass the string to a js var then that would be great also. 如果有可能让PHP做一些肮脏的工作,然后将字符串传递给js var,那也很好。 In the end it must be a string, or an array of strings. 最后,它必须是一个字符串或字符串数​​组。

I've seen a lot of people recommending getting familiar with the Google Docs API, but really, I'm a nooby with both CakePHP and javascript and its taken a lot of work to get this far, my head is full to bursting point and I just dont think i'll be able for another big reading session, time is running out on my project. 我见过很多人建议您熟悉Google Docs API,但实际上,我对CakePHP和javascript都很陌生,为此付出了很多努力,我的头脑已经爆满了,我只是不认为我可以参加另一个大型阅读会议,所以我的项目时间已经用完了。 Also, dont assume I know ANYTHING, a complete idiots response would be greatly appreciated, thanks in advance. 另外,不要以为我什么都知道,一个完整的白痴反应将不胜感激,在此先感谢。

If the file is local to the where your application is being served (is on the same server), you can use simple PHP file I/O. 如果该文件位于服务应用程序所在的本地文件(位于同一服务器上),则可以使用简单的PHP文件I / O。

<?php
$filename = "/YOUR/FILE/URL/HERE.csv";
$file = fopen( $filename, "r" );
if( $file == false ) {
    echo "Error!";
    exit();
}
$csv_string = fread( $file, $filesize );
fclose( $file );
?>

mapbox.markers.layer().csv("<?php echo $csv_string; ?>");
//Make sure you put the quotes around the php tag. Otherwise the JavaScript will not recognize it as a string.

(Derived heavily from http://www.tutorialspoint.com/php/php_files.htm ). (大量源自http://www.tutorialspoint.com/php/php_files.htm )。 I hope this is what you're looking for. 我希望这是您要寻找的。

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

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