在 PHP 中从文件导出中删除引号

Remove quotes from file export in PHP

提问人:gmoney 提问时间:2/2/2020 更新时间:2/2/2020 访问量:99

问:

我一直在为 Twilio 的报告导出代码进行一些自定义。我被困在如何删除出现在“正文”字符串中的文本中的引号上。我尝试了 str_replace( '“','',$sms )->body 和 addslashes($sms) ->body,但我做错了什么。你能帮我找到一个解决方案来删除正文中的所有引号吗?完整代码如下:

<?php
/**
* Download the library from: https://github.com/twilio/twilio-php
* Copy the 'Twilio' folder into a directory containing this file.
*/

require __DIR__ . '/Twilio/autoload.php';

use Twilio\Rest\Client;

/* Your Twilio account sid and auth token */
$account_sid = "hidden";
$auth_token = "hidden";

/* Download data from Twilio API */
$client = new Client($account_sid, $auth_token);
$messages = $client->messages->stream(
  array(
  'dateSentAfter' => '2020-01-01',
  'dateSentBefore' => '2020-02-01'
  )
);

/* Browser magic */
$filename = $account_sid."_sms.csv";
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename={$filename}");

/* Write headers */
$fields = array( 'From', 'To', 'Body', 'Status', 'Date Sent', 'SMS Message SID' );
echo '"'.implode('","', $fields).'"'."\n";

/* Write rows */
foreach ($messages as $sms) {
  $row = array(
    $sms->from,
    $sms->to,
    $sms->body,
    $sms->status,
    $sms->dateSent->format('Y-m-d H:i:s \G\M\T'),
    $sms->sid
  );

  echo '"'.implode('","', $row).'"'."\n";
}
PHP 字符串 变量格式 引号

评论

1赞 u_mulder 2/2/2020
str_replace( '"','',$sms->body )

答:

1赞 Sammitch 2/2/2020 #1

不要编写自己的序列化程序,已经存在的序列化程序已经内置了转义逻辑,涵盖了所有情况,并正确地覆盖了它们。

https://www.php.net/manual/en/function.fputcsv.php

“但我不是在写文件!” 是的,你是。一切都是一个文件。

将回声替换为:

fputcsv(STDOUT, $row);

评论

0赞 gmoney 2/2/2020
替换整行或插入此行以仅替换回声功能?如果我替换整行,则在代码运行时会出现网关超时。