Run PHP to pull google sheets CSV

im working with the code below, it works in a regular php document but when i use it in wordpress it doesnt work. i have a plugin installed to allow me to run php code on pages. any help is appreciated.

<?PHP
function readCSV($csvFile){
    $file_handle = fopen($csvFile, 'r');
    while (!feof($file_handle) ) {
        $line_of_text[] = fgetcsv($file_handle, 1024);
    }
    fclose($file_handle);
    return $line_of_text;
}


// Set path to CSV file
$csvFile = 'https://docs.google.com/spreadsheets/d/1oC88LWXn4SgvVzK3wQAojXk7UM5tDjuWuMZDAjQTGjw/pub?gid=0&single=true&output=csv';

$csv = readCSV($csvFile);
echo '<pre>';
print_r($csv);
echo '</pre>';
?>
<?php

print_r($csv[0][1]);//prints row 1, column 1

?> <?php

print_r($csv[0][2]);//prints row 1, column 1

?>

Related posts

1 comment

  1. Your fopen function makes a call to an external document.

    It’s very common for shared hosting providers to disable allow_url_fopen in php.ini to stop Remote File Inclusion attacks.

    You need to instead use cURL to get the data back. Here’s an illustration. I’ve chosen to use the php://temp stream to store the data returned, as we don’t need it locally. This will allow us to read from the stream pointer and then loop it, pushing each line into the $line_of_text[] array.

    function readCSV($url){
        $fh = fopen('php://temp', 'w+');
        $ch = curl_init(); 
        curl_setopt($ch, CURLOPT_URL, $url); 
        curl_setopt($ch, CURLOPT_FILE, $fh); 
        curl_close($ch);      
    
        rewind($fh);
    
        while ($line = fgetcsv($fh, 1024)) {
            $line_of_text[] = $line;
        }
    
        fclose($f);
    
        return $line_of_text;
    }
    

    Alternative and less recommended solution

    Find and locate the loaded php.ini for your site, and modify allow_url_fopen to 1.

Comments are closed.