如何使用PHP将URL编码为JSON

时间:2019-04-02 07:07:23

标签: php json dialogflow

我想从我的php网页中将URL和一些文本输出作为json输出,为此,我在php中使用了json_encode()函数,以下是我的php数组,它将转换为json:< / p>

$output= array (
  'payload' => 
  array (
    'google' => 
    array (
      'expectUserResponse' => true,
      'richResponse' => 
      array (
        'items' => 
        array (
          0 => 
          array (
            'simpleResponse' => 
            array (





              'textToSpeech' => '<speak>some text... <audio src=\"https://example.com\"></audio></speak>',
              'displayText' => 'some text...',





            ),
          ),
        ),
        'suggestions' => 
        array (
          0 => 
          array (
            'title' => 'cancel',
          ),
        ),
      ),
    ),
  ),
);

echo json_encode($output);

并且此php代码产生以下json输出:

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "richResponse": {
        "items": [
          {
            "simpleResponse": {





              "textToSpeech": "<speak>some text... <audio src=\\\"https://example.com\\\"></audio></speak>",
              "displayText": "some text..."





            }
          }
        ],
        "suggestions": [
          {
            "title": "cancel"
          }
        ]
      }
    }
  }
}

但是我需要以下json输出:

{
  "payload": {
    "google": {
      "expectUserResponse": true,
      "richResponse": {
        "items": [
          {
            "simpleResponse": {





              "textToSpeech": "<speak>some text... <audio src=\"https://example.com\"></audio></speak>",
              "displayText": "some text..."





            }
          }
        ],
        "suggestions": [
          {
            "title": "cancel"
          }
        ]
      }
    }
  }
}

我不了解如何根据我的要求将URL放在json中。

2 个答案:

答案 0 :(得分:0)

如果您不想转义的斜线,可以使用

json_encode($response, JSON_UNESCAPED_SLASHES);

告诉PHP不要转义这些斜杠。

但是,如果您在谈论反斜杠,则必须像这样将其转义,因为PHP会将其解释为转义字符。您随时可以在接收端手动将其删除。

答案 1 :(得分:0)

'<speak>some text... <audio src=\"https://example.com\"></audio></speak>',

双引号不需要在此处转义。字面意义上的反斜杠是因为字符串是单引号。反斜杠只能在单引号引起来的字符串中转义一个单引号或另一个反斜杠。其他任何后续字符都会导致文字反斜杠。

'<speak>some text... <audio src="https://example.com"></audio></speak>'(不转义)或 "<speak>some text... <audio src=\"https://example.com\"></audio></speak>"(双引号)应提供所需的输出。