如何在 php 中对原始 json 字符串进行编码

我有JSON,它已保存在我网站的文本框中,并保存到下面的数据库中。


{"@type":"GOOOGLE.COM","@id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"@id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}

我想将其转换为PHP中的正确外观,如下所示:


{"@type":"GOOOGLE.COM","@id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"@id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}

我试着做了一个json_encode但它不起作用。如何将带有所有这些转义引号等的字符串转换为PHP中的普通json字符串?


我试过这样:


  $str = "{"@type":"GOOOGLE.COM","@id":"GOOGLE","url":"GOOGLE","inLanguage":"en-US","name":"dfghjk | Bloomberg Professional Services","isPartOf":{"@id":"GOOGLE,"datePublished":"2020-02-11T21:51:45+00:00","dateModified":"2020-02-11T21:51:45+00:00"}]}"

  $data = json_encode($str, true);  

  return $data; 


千万里不及你
浏览 105回答 1
1回答

一只名叫tom的猫

您需要将 HTML 实体解码回字符:https://www.php.net/manual/en/function.htmlspecialchars-decode.php  $json = htmlspecialchars_decode($str, true);  // valid json string  $data = json_decode($json); // convert json to php data structure  return $data;
打开App,查看更多内容
随时随地看视频慕课网APP