0

When I'm writing to "Text.csv" the string: ' my name is "Robert" ', the string that is added to Text.csv looks like: my name is /"Robert/" ' .

In my code, before writing to the csv file, the $_POST var is being escaped with the php function htmlspecialchars(). But is still showing the slashes.

What can the problem be?

Reading from Text.csv section:

$myFile = "Text.csv";
$fh = fopen($myFile, 'r') or die("can't open file");
for ($i=0 ; $i<5 ; $i++)
{
  $line=fgets($fh);

  if ($line)
  {
  $line_of_text =  explode(",", $line);
echo htmlspecialchars($line_of_text[0]).'<br />';
echo htmlspecialchars($line_of_text[1]).'<br />';
echo htmlspecialchars($line_of_text[2]).'<br />';
echo htmlspecialchars($line_of_text[3]).'<br />';
echo htmlspecialchars($line_of_text[4]).'<br />';
} } fclose($fh);

Writing to Text.csv section:

header('Content-type: text/html; charset=UTF-8');
$myFile = "Text.csv";
$fh = fopen($myFile, 'w') or die("can't open file");
for ($i=1 ; $i<26 ; $i++)
{
$str='l'.intval(($i-1)/5).'f'.(($i-1)%5);

if (($i%5)==0)
    {
    $stringData = $_POST[$str].PHP_EOL;
   fwrite($fh, htmlspecialchars($stringData));
    }
Else
    {
    $stringData = $_POST[$str].",";
    fwrite($fh, $stringData);
    }
}

fclose($fh);
Tzahi Serruya
  • 147
  • 2
  • 11

1 Answers1

0

I think you should use htmlentities() to encode the HTML characters and for decode use html_entity_decode().

Try this code.

Reading from Text.csv section:

$myFile = "Text.csv";
$fh = fopen($myFile, 'r') or die("can't open file");
for ($i=0 ; $i<5 ; $i++)
{
  $line=fgets($fh);

  if ($line)
  {
  $line_of_text =  explode(",", $line);
  echo html_entity_decode($line_of_text[0]).'<br />';
  echo html_entity_decode($line_of_text[1]).'<br />';
  echo html_entity_decode($line_of_text[2]).'<br />';
  echo html_entity_decode($line_of_text[3]).'<br />';
  echo html_entity_decode($line_of_text[4]).'<br />';
}
} fclose($fh);

Writing to Text.csv section:

header('Content-type: text/html; charset=UTF-8');
$myFile = "Text.csv";
$fh = fopen($myFile, 'w') or die("can't open file");
for ($i=1 ; $i<26 ; $i++)
{
$str='l'.intval(($i-1)/5).'f'.(($i-1)%5);

if (($i%5)==0)
{
    $stringData = $_POST[$str].PHP_EOL;
    fwrite($fh, htmlentities($stringData, ENT_QUOTES));
}
else
{
    $stringData = $_POST[$str].",";
    fwrite($fh, htmlentities($stringData, ENT_QUOTES));
}
}

fclose($fh);
Jahanzeb
  • 613
  • 4
  • 11