Here is the code which I am using to pull data from a public google docs spreadsheet (exported as a CSV).
<?php
// link to Google Docs spreadsheet
$url='https://docs.google.com/spreadsheet/pub?key=xxxx&output=csv';
// open file for reading
if (($handle = fopen($url, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$totalrows = count($data);
for ($row=0; $row<=$totalrows; $row++)
{
if (strlen($data[$row])>0)
{
$firstname = $data[1];
$surname = $data[1];
echo $firstname;
echo $surname;
}
}
echo '<pre>';
print_r($data);
echo '</pre>';
}
fclose($handle);
}
exit;
?>
The output I am getting is as follows:
MartinMartin
Array
(
[0] => Firstname
[1] => Martin
)
CarlinCarlin
Array
(
[0] => Surname
[1] => Carlin
)
I am just confused as to what I am doing wrong, I am looking to be able to set the data as variables so that they can be echoed later in the script.
i.e.
<?php echo $firstname; ?>
Should echo Martin, not MartinMartin.
This is how the data is stored in the spreadsheet:
A B
1 Firstname Martin
2 Surname Carlin
Any help appreciated!
Update
Changed the structure now as follows (sorry for the long-windedness and repetition):
// open file for reading
if (($handle = fopen($url, "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
for ($row = 0; $row < count($data); $row += 2)
{
$firstname = $data[$row][1];
$surname = $data[$row + 1][1];
}
}
fclose($handle);
}
echo 'Firstname: '.$firstname.'<br /><br />';
echo 'Surname: '.$surname;
exit;
You are getting MartinMartin because you are setting firstname and surname to the same data[1] value and echoing both out together per row iteration. If you comment out echo $surname, you will find that it does just output Martin. Bear in mind that Martin’s surname Carlin is on a different row to his first name too, so you won’t be able to just do $surname = $data[1] to get it. You would need to look ahead to the next row to get his surname. You’d probably want to iterate the $row array in 2-step fashion so you could index $data[$i][1] and $data[$i + 1][1] for first name and surname.