我写了一个脚本来下载Google工作表,然后将该工作表上传到我的dadabase。
除了数据现在正在上传到我的数据库之外,一切似乎都工作正常。
我导航到该文件夹,然后运行以下命令:
php -f updatedatabase.php
这是我编写的脚本(用实际的密钥填充了googel工作表密钥-我测试了链接,并且该链接可以正常工作,并且出于安全原因,数据库凭据已加注星标):
<?php
$datas = file_get_contents("https://docs.google.com/spreadsheets/d/1fOe2fz8PmYzTWU7l_KboHdv0zP0KZkhcJUTGJDUXaKk/gviz/tq?tqx=out:csv&sheet=All%20Items&range=A:G");
$datas = explode( PHP_EOL, $datas );
//FORMAT ("Name1", "Image1", "Description1", "Rarity1", "Price1", "Status1", "Store1"), ("Name2", "Image2", "Description2", "Rarity2", "Price2", "Status2", "Store2").....
// Info to connect to the database
$servername = ".com";
$dbusername = "";
$password = "!19";
$dbname = "";
$con=mysqli_connect( $servername, $dbusername, $password, $dbname );
mysqli_query( $con, "TRUNCATE TABLE Items" );
foreach ( $datas as $data ) {
echo $data . "\n";
mysqli_query( $con, "INSERT INTO Items (Name,Image,Description,Rarity,Price,Status,Store) VALUES " . $data );
}
mysqli_close($con);
?>
答案 0 :(得分:1)
您的data
字符串格式不正确:
$csvData = file_get_contents("https://docs.google.com/spreadsheets/d/1fOe2fz8PmYzTWU7l_KboHdv0zP0KZkhcJUTGJDUXaKk/gviz/tq?tqx=out:csv&sheet=All%20Items&range=A:G");
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
// format the data string
// work with PHP7.0 or later
$datas = array_map(function ($data) {
$dataString = implode("','", $data);
return "('$dataString')";
}, $array);
// remove the head line
array_shift($datas);
// Info to connect to the database
$servername = "192.168.10.10";
$dbusername = "homestead";
$password = "secret";
$dbname = "gooledoc";
$con = mysqli_connect($servername, $dbusername, $password, $dbname);
mysqli_query($con, "TRUNCATE TABLE Items");
foreach ($datas as $data) {
echo $data . "\n";
$result = mysqli_query($con, "INSERT INTO `Items` (`Name`,`Image`,`Description`,`Rarity`,`Price`,`Status`,`Store`) VALUES " . $data);
var_dump($result);
}
mysqli_close($con);