How do I properly format a JSON payload in PHP without invalid whitespace for a REST API post call?

huangapple go评论53阅读模式
英文:

How do I properly format a JSON payload in PHP without invalid whitespace for a REST API post call?

问题

需要在 JSON 字符串中删除空白/无效的空格,以便将其作为 REST API POST 调用的有效负载传递。

当前显示为:

{ "channel":{"id" : 6},"entryType" : {"id" : 1},"contentType": {"id": 2},"text":"
tttttt
" }

期望的结果是:

{ "channel":{"id" : 6}, "entryType" : {"id" : 1}, "text" : "Test1" }

将值分配给“text”键是动态的。

英文:

Need to remove whitespaces/invalid spaces in json string to pass as payload in rest api post call.

Currently it displaying:-

{ "channel":{"id" : 6},"entryType" : {"id" : 1},"contentType": {"id": 2},"text":"
tttttt
" }

Expecting:-

{ "channel":{"id" : 6}, "entryType" : {"id" : 1}, "text" : "Test1" }

Assigning the value to the "text" key is dynamic.

答案1

得分: 1

如果您想删除文本字段开头或结尾的空格,您可以使用 trim 函数:

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

$text = ' this is a test ';
$text = trim($text);
// $text ---> 'this is a test'

但是,如果目标是删除所有空格,我会使用 str_replace 函数:

https://www.php.net/manual/en/function.str-replace.php

$text = ' this is a test ';
$text = str_replace(' ', '', $text);
// $text ---> 'thisisatest'

这将消除所有空格,甚至文本之间的空格,所以如果您想传递完整的句子或段落,trim 将是一个更好的选项。

英文:

If you want to remove whitespaces at the beginning or end of the text field, you can use trim:

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

$text = ' this is a test ';
$text = trim($text);
// $test ---> 'this is a test'

But, if the objective were remove all whitespaces, I would use str_replace:

https://www.php.net/manual/en/function.str-replace.php

$text = $text = ' this is a test ';
$text = str_replace(' ', '', $text);
// $test ---> 'thisisatest'

This will eliminate all spaces, even between of the text, so if you want pass complete sentences or paragraphs, trim will be a better option.

huangapple
  • 本文由 发表于 2023年5月28日 11:12:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76349790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定