简体   繁体   中英

PHP Escaping JSON string for CSV export

I have an array where one of the elements value is a long JSON string

foreach ( $results as $data ) {
    // Put the data into the stream
    fputcsv($fh, $data);
}

I need a way to escape the JSON string because currently in my CSV export the backslashes in the JSON string are starting new columns

Thanks

Alex

Yes you can do so by using

foreach ( $results as $data ) {
    if(is_array(json_decode($data,true))) continue ;
    fputcsv($fh, $data);
}

UPDATE from the last comment ::

Looks like your $data has an array instead of JSON so in this case you can just do

foreach ( $results as $data ) {
        if(is_array($data)) continue ;
        fputcsv($fh, $data);
    }

AND combining both we can have following where it will escape both JSON and ARRAY

foreach ( $results as $data ) {
        if(is_array($data)) continue ;
        if(is_array(json_decode($data,true))) continue ;
        fputcsv($fh, $data);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM