简体   繁体   English

PHP转义JSON字符串以进行CSV导出

[英]PHP Escaping JSON string for CSV export

I have an array where one of the elements value is a long JSON string 我有一个数组,其中的元素值之一是一个很长的JSON字符串

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 我需要一种转义JSON字符串的方法,因为当前在我的CSV导出中,JSON字符串中的反斜杠开始新的列

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 看起来您的$ data具有数组而不是JSON,因此在这种情况下,您可以

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 并结合两者,我们可以得到以下将逃逸JSON和ARRAY的地方

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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