mcguinnsoft
mcguinnsoft

Reputation: 45

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. 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.

Upvotes: 0

Views: 5371

Answers (2)

tmcw
tmcw

Reputation: 11882

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

Upvotes: 0

Andy Hill
Andy Hill

Reputation: 316

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.

Upvotes: 0

Related Questions