Hi,
I make a script that import text file that contain my friends phone numbers
the format of text file is this

someone:0123456789
someone2:0123456789

and I use following code to read it

			$myFile = "fileTemp/$fileLocation";
			$fh = fopen($myFile, 'r');
			$Data = fread($fh, filesize($myFile));
			fclose($fh);
                        $queryArray = explode ( "\r\n", $Data );

now i would like that $querArray key is name and value it's number 😕
is that possible thank you 🆒

    You might want to take a look at [man]fgetcsv/man, using the optional 3rd parameter to specify ":" as the delimiter.

      You can do that, using file() function, that returns an array, where every line is an element of the array.

      Example :

      $text = array();
      $text = file('test.txt', FILE_IGNORE_NEW_LINES);

      Then, you just have to iterate the array.

      foreach($text as $t) {
          $new = explode(':', $t); // We seperate every line..
          $names[] = $new[0]; // Save the names in $names
          $phones[] = $new[1]; // Save the phones in $phones
      }
      

      It would be like this...

      $names = array();
      $phones = array();
      $new = array();
      $text = array();
      $text = file('test.txt', FILE_IGNORE_NEW_LINES);
      foreach($text as $t) {
          $new = explode(':', $t);
          $names[] = $new[0];
          $phones[] = $new[1];
      }
      
      print_r($names);
      print_r($phones);
      

      Hope it works for you.

      See you

        Under_Control;10930978 wrote:

        but it's not csv file it's txt

        A CSV file is a text file. As I stated in my first reply, you can use the optional 3rd argument to fgetcsv to use a character other than the comma as your field delimiter, allowing you to use it to parse, for instance, tab-delimited files, or in this case colon-delimited.

        Untested:

        if($fh = fopen('path/to/file'))
        {
           while(($line = fgetcsv($fh, 9999, ':') !== false)
           {
              if(count($line) >= 2)
              {
                 $sql = sprintf(
                    "INSERT INTO table_name (`name`, `phone`) VALUES('%s', '%s')",
                    mysql_real_escape_string(trim($line[0])),
                    mysql_real_escape_string(trim($line[1]))
                 );
                 mysql_query($sql);
              }
           }
        }
        

        If the file is large, you might want to add some additional logic to create an arbitrary number of VALUES() groups for the INSERT statement, so that you only execute 1 query for every n rows in the file.

          If this is going to be a one-time import and you have root access to the MySQL server, consider using the MySQL function LOAD DATA LOCAL INFILE, which can handle CSV files and insert the data directly to your database without PHP interference.

            Write a Reply...