Answer the question
In order to leave comments, you need to log in
How to transfer a JSON file with a large number of lines to MySQL?
Good afternoon, there is a JSON base of this type:
{"_id":707860,"name":"Hurzuf","country":"UA","coord":{"lon":34.283333,"lat":44.549999}}
{"_id":519188,"name":"Novinki","country":"RU","coord":{"lon":37.666668,"lat":55.683334}}
{"_id":1283378,"name":"Gorkhā","country":"NP","coord":{"lon":84.633331,"lat":28}}
{"_id":1270260,"name":"State of Haryāna","country":"IN","coord":{"lon":76,"lat":29}}
{"_id":708546,"name":"Holubynka","country":"UA","coord":{"lon":33.900002,"lat":44.599998}}
Answer the question
In order to leave comments, you need to log in
It is better to make a query not for each row, but to form batch queries INSERT INTO (...) VALUES (...), (...), ...
In this case, you must take into account the maximum length of a MySQL query set in the 'max_allowed_packet' variable .
Before running the script, it is better to disable all indexes on the table, then enable them back.
Thanks to those who tried to help, I wrote this code:
$connect = mysql_pconnect("localhost","root","") or die ("Невозможно подключение к MySQL"); // Соединяемся с базой mysql (адрес, имя пользователя, пароль)
mysql_select_db("weather", $connect) or die ("Невозможно открыть таблицу с данными"); // подключаемся к базе (имя базы, $connect)
mysql_query("SET NAMES 'utf8'", $connect); // задаем кодировку
$filename = "template/city.list.json"; // местонахождения json базы
if ($file = fopen($filename, "r")) { // открываем json файл
while (!feof($file)) { // проходимся циклом пока не достигнем конца файла
$line = fgets($file, 1024); // возвращаем каждую строку файла
$data = json_decode($line, true); // декодируем json массив в php массив
$result = mysql_query ("INSERT INTO weather_country (id, name, country, lon, lat) VALUES ('".$data['_id']."', '".$data['name']."', '".$data['country']."', '".$data['coord']['lon']."', '".$data['coord']['lat']."')"); // записываем полученые данные в таблицу weather_country.
}
}
if (isset($result)){ // выводим результат работы скрипта
echo "Добавлено в базу данных.";
} else {
echo "Недобавлено в базу данных.";
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question