Zhang Zhenyun
Zhang Zhenyun

Reputation: 23

php - export string with both double quotes and comma into csv format

I know how to handle string with comma into csv, and string with double quote into csv,

but if a string with both comma and double quote, how to convert it ?

like:

Seminar on "Changing Myanmar: Institutions, Personalities and Expectations" 10 Feb 2012;

by default I added " " to the string, so it can convert to csv file with comma,

but if this string also contains "", then the field separate into two fields in csv.

I tried this:

"Seminar on """Changing Myanmar: Institutions, Personalities and Expectations""" 10 Feb 2012"

but it is wrong...

Upvotes: 2

Views: 5111

Answers (2)

napolux
napolux

Reputation: 16074

I think that using fputcsv() is the best way to avoid any problem.

Upvotes: 1

web-nomad
web-nomad

Reputation: 6003

This works:

<?php
@unlink( 'test.csv' );
$fp = fopen( 'test.csv', 'w' );

$text = '"Changing Myanmar: Institutions, Personalities and Expectations"';

fwrite( $fp, '"'. str_replace( '"', '""', $text ) . '", "test"' . "\n" );

fclose( $fp );
?>

Reading from this csv file:

$fp = fopen( 'test.csv', 'r' );

while( ( $data = fgetcsv( $fp, '', ',' ) ) !== false ) {
    echo $data[0];
}

fclose( $fp );

Output - "Changing Myanmar: Institutions, Personalities and Expectations"

Hope this helps.

Upvotes: 0

Related Questions