<?php ini_set('memory_limit', '1024M'); define("ROOT",realpath(__DIR__).DIRECTORY_SEPARATOR); $file = ROOT.'data.txt'; if(is_file($file)){ $csv = array_map('str_getcsv', file($file)); $arr = ''; if(is_array($csv)){ foreach($csv as $line){ $arr[] = array('guid'=>$line[0],'icon'=>$line[1]); } } $head = 'INSERT INTO `tab_icon` (`id`, `icon`) VALUES'; foreach($arr as $ln){ $head .= "('{$ln['guid']}','{$ln['icon']}'), \n"; } $head = substr($head, 0, -3).';'; file_put_contents(ROOT.'tab_icon.sql',$head); }?> 

My code to which I read in-line file txt File contents:

1 weapon_small_sword_i00
2 weapon_long_sword_i00
3 weapon_broad_sword_i00
4 weapon_club_i00
5 weapon_mace_i00

etc.

Tell me how I can extract my data in this way - ( id , icon ). In my case, everything is saved line by line in 1 column, and the second is empty

  • in the sense of line by line? - Naumov
  • In this example, the sql file is created like this: ('2 weapon_long_sword_i00', ''), but I need it like this ('2', 'weapon_long_sword_i00'), - Elizaveta

1 answer 1

Something like this you can get the data:

 <?php ini_set('memory_limit', '1024M'); define("ROOT",realpath(__DIR__).DIRECTORY_SEPARATOR); $file = ROOT.'data.txt'; if(is_file($file)){ $data = file_get_contents($file); $rows = explode(PHP_EOL, $data); $head = 'INSERT INTO `tab_icon` (`id`, `icon`) VALUES'; foreach ($rows as $k => $row){ $cell = explode(' ', $row); $head .= "('{$cell[0]}','{$cell[1]}')"; if ($k < count($rows)) { $head .= ", \n"; } } file_put_contents(ROOT.'tab_icon.sql',$head); } ?> 
  • I didn’t quite understand how it was. Could you show me with an example of my code? - Elizaveta
  • Corrected the answer. I have not worked with php for many years, I don’t know that it has a csv parser and I don’t know the reasons for its incorrect operation. Therefore, I use the usual string parser and spaces. I can also err somewhere in the syntax, for example, I don’t know what the curly braces are {} - Artem Gorlachev
  • Your code unfortunately gave no results (('2 weapon_long_sword_i00', ''), - Elizaveta
  • So the explode line did not work on the space, maybe there is some other separator character like tabulation? - Artem Gorlachev
  • Removed extra lines, tabs, etc., now seems to be a space, but there is no result as before ( - Elizabeth