doubi6215 2015-08-04 05:27
浏览 544

如何在PHP中创建有效的换行JSON?

I'm currently trying to send emails via the Sendgrid SMTP API. I have a "name" substitution which replaces tags in the email with recipient's names. However, I'm running into an issue where my SMTP JSON gets declined as invalid by Sendgrid.

The issue is because the names have spaces, and the Swift mailer wraps the lines here. The linebreaks end up being in the middle of names, making those strings invalid JSON leading to Sendgrid turning that email down. I'm generating the header using Sendgrid's own SMTP API PHP library but this does not do the linewrapping for you.

I'm trying to find a way to wrap my JSON in a way that doesn't make it invalid. I haven't been able to find any PHP solutions. Sendgrid themselves give a PERL regex example, which I unsuccessfully attempted to do in PHP.

I also found a Ruby solution that is promising, but my application server supports ONLY PHP. This is the Ruby solution I found.

This is the code I'm using to send the emails.

<?php
//...
$header = new Header(); // This is the sendgrid API header class
$header->setTos(array_column($subscribers, 'email'));
$header->addSubstitution('-SubscriberName-', array_column($subscribers, 'name'));
$header->addSubstitution('-SubscriberId-', array_column($subscribers, 'id'));

// $message is a SwiftMessage
$message->getHeaders()->addTextHeader(strtoupper(Header::NAME), $header->jsonString());

This is how the header value is set, according to logs. I've removed personal data but you can see how "The( )Shop" would cause the aforementioned invalid JSON error. This happens many times through out the name substitutions.

X-SMTPAPI: {"to":[/* emails removed, but there were no spaces so all emails were on one very long line */],"sub":{"-SubscriberName-":["Joseph","Alexandra","Michelle","Nicky","Des","Clive","Peter","Robert","Tedy","Terry","Terry","Terry","Tessa","The 
Shop","Thomas","Tim","Tim","Tina","Tina","Tobias","Tom","Tommy", //...
  • 写回答

2条回答 默认 最新

  • douhan8581 2015-08-04 06:00
    关注

    May be what you need is json_encode with JSON_PRETTY_PRINT as discussed here: Pretty-Printing JSON with PHP

    评论

报告相同问题?

悬赏问题

  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。