【问题标题】:Remove quotes from file export in PHP从 PHP 中的文件导出中删除引号
【发布时间】:2020-05-18 03:38:09
【问题描述】:

我一直在对 Twilio 的报告导出代码进行一些自定义。我被困在如何删除出现在“body”字符串中的文本中的引号。我试过 str_replace( '"','',$sms )->body 和 addlashes($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";
}

【问题讨论】:

  • str_replace( '"','',$sms-&gt;body )

标签: php string variables formatting quotes


【解决方案1】:

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

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

“但我没有写入文件!”是的,你是。 Everything is a file.

将您的回声替换为:

fputcsv(STDOUT, $row);

【讨论】:

  • 替换整行或插入此行以仅替换 echo 函数?如果我替换整行,代码运行时会出现网关超时。
猜你喜欢
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-11
  • 1970-01-01
  • 2014-05-05
  • 2017-02-07
  • 1970-01-01
相关资源
最近更新 更多