8

What is the right way to specify the end of line character of a CSV file with PHP. I have this script to write the CSV file.

<?php

ini_set('display_errors', 1);
error_reporting(E_ALL);

include_once("phpshared.php");

function get_node_urls( $nodeid ) {

$nodes = new SimpleXMLElement('linkcards.xml', null, true);
$nodesarray = $nodes->xpath("//LINKCARD[@ID='$nodeid']");  

$linkstring = '';
$node = $nodesarray[0]; 
$i = 0;
foreach($node->LINKS->LINK as $url)
{ 
       $linkstring .= $i.','.$url['ID'].','.$url->TITLE.','.$url->URL.'\r\n';
       $i++;
}
echo $linkstring;

}

echo get_node_urls(trim($_REQUEST['nodeid']));

?>

If I load $linkstring there is no carriage return at the end of each line. The lines should be:

0, id1, http://link1.com
1, id2, http://link2.com

Instead they are:

0, id1, http://link1.com\r\n1, id2, http://link2.com

The CSV reader reads that line as:

id1 http://link1.com\r\n1

Is there a different way of writing the end of line for a CSV?

2 Answers 2

12

\r\n needs to be enclosed in " instead of ' so that escape sequences will be interpreted (see documentation):

$linkstring .= $i.','.$url['ID'].','.$url->TITLE.','.$url->URL."\r\n";
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Arrggghhhh! Thanks so much, the end of line handling in PHP is absolutely ludicrous.
5

After look all over the web I found that the problem is due the Auto Detect Line Ending not being enable. Just set it on your code and it should work. It worked for me.

ini_set('auto_detect_line_endings',TRUE);

With the auto_detect enable you can parse the file as a regular file using

$lines = file('your_csv_file.csv');

On my case I'm already parsing the CSV lines using str_getcsc

function parse_my_csv($filename) { 
    $lines = file($filename);
    $data = array();
    for($i=0;$i<count($lines);$i++) { 
       array_push($data, str_getcsv($lines[$i]));
    }
 return $data;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.