从外部URL将CSV文件上传到mysql

时间:2019-03-25 17:26:37

标签: javascript php mysql google-sheets

例如,我有一个来自Google表格的网址,该网址将表格导出到CSV文件:

https://docs.google.com/spreadsheets/d/{key}/gviz/tq?tqx=out:csv&sheet={sheet_name}

我想要某种机制来处理外部CSV文件,以将其插入MySQL的表中。

我对从哪里开始没有丝毫想法。

更新25/03/2019:这是我的最新进展,这要归功于一些答案!我仍然必须将CSV导入MySQL。

 <?php

$conn = new mysqli($servername, $username, $password, $dbname);

$array = str_getcsv(file_get_contents("https://docs.google.com/spreadsheets/...."));

var_dump($array);

    $name = tempnam('/','csv');
    $fp = fopen($name, 'w'); 

    // $array = str_replace('"', '', $array);

   fputs($fp, implode($array, ',')."\n");


$sql = "DELETE FROM conceptos";
$result = $conn->query($sql);


$sql = "LOAD DATA LOCAL 
    INFILE '$name' INTO TABLE conceptos FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES";

fclose($fp);

?>

我现在正在创建一个临时文件以尝试使用LOAD DATA,但是我遇到了其他错误,例如找不到文件,我只能从命令行看到此错误,而不能直接从我的PHP代码看到

1 个答案:

答案 0 :(得分:1)

对我来说听起来像3个步骤。

  1. 查询URL并将结果读入字符串变量。 (请参见此处:website query, php
  2. 解析包含CSV数据的字符串(请参见此处:https://www.php.net/manual/en/function.str-getcsv.php
  3. 插入您的MySQL数据库(请参见此处:https://www.w3schools.com/php/php_mysql_insert.asp

像这样解析:

<?php 
$Data = str_getcsv($CsvString, "\n"); //parse the rows 
foreach($Data as &$Row) $Row = str_getcsv($Row, ";"); //parse the items in rows 
?>

祝你好运!