1

I have a Excel data converted from XLSX to CSV, then I need to upload it to my site. The data shown like this on CSV but changed after upload.

// On Excel (CSV)
Row   Description
 1    Enjoy this life without drugs
 2    Life is so short, so enjoy it

After uploading to site and inserted to MySQL it's look like this.

// On MySQL
Row   Description
 1    Enjoy?this life without?drugs
 2    Life is?so?short, so?enjoy it

// On PHP ( (echo loop).
Row   Description
 1    Enjoy�this life without�drugs
 2    Life is�so�simple, so�enjoy it

I was checked on my CSV, it just space that changed into ? and . So, I'm trying to replace that but all failed using :

// $the_string = Line of text Description.
1. str_replace("�", " ", $the_string);
2. str_replace("&#65533", " ", $the_string);
3. str_replace("&#xfffd", " ", $the_string);
4. str_replace("?", " ", $the_string");

But, If I'm test it only on <?php str_replace("�", " ", "a�b"); ?>, It's working.

I don't know where is the mistake.

This is my source code :

public function upload()
{
   $config = array(
      "upload_path" => "./uploads/",
      "allowed_types" => "csv"
   );
   $this->load->library("upload", $config);
   $this->load->helper("file");
   $this->upload->initialize($config);
   $upload = $this->upload->data();
   $file = base_url()."uploads/{$upload['file_name']}";
   $file_handle = fopen($file, "r");
   $check_line = 0;
   while ( ! feof($file_handle))
   {
      $line_of_text = fgetcsv($file_handle, 1024);
      $check_line++;
   }
   fclose($file_handle);
   if ($check_line > 1)
   {
      $file_handle2 = fopen($file, "r");
      while ( ! feof($file_handle2))
      {
         $line_of_text = fgetcsv($file_handle, 1024);
         $description = $line_of_text[1];
         $this->model->insert_description($description);
      }
      fclose($file_handle);
   }
}
Zinc
  • 385
  • 1
  • 5
  • 19

1 Answers1

1

Try with preg_replace():

preg_replace('/\x{FFFD}/u', ' ', $the_string);

Try it here.

Attention: This will remove the character from the string, but ONLY if it is the real character stored in the string.

The character may appear in substitution of every character that isn't encoded properly accordingly with the encoding used by, in this case, PHP.

To remove all non-printable characters use this:

preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $the_string);

Try it here.

user2342558
  • 5,567
  • 5
  • 33
  • 54