Reading CSV file into javascript string or array

元气小坏坏 提交于 2019-12-25 15:50:09

问题


I'm having a very specific problem so I hope someone can help. I'm building a map app with a CakePHP backend framework. 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. 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, e.g. 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? 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. 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. Also, dont assume I know ANYTHING, a complete idiots response would be greatly appreciated, thanks in advance.


回答1:


use reqwest: here's a working example of loading a separate csv file.




回答2:


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
$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). I hope this is what you're looking for.



来源:https://stackoverflow.com/questions/11951534/reading-csv-file-into-javascript-string-or-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!