【问题标题】:JSON object as php string [duplicate]JSON对象作为php字符串[重复]
【发布时间】:2012-04-22 21:21:11
【问题描述】:

可能重复:
Convert a JSON into a UTF-8 string

我正在缓存一些 twitter 提要以供长期使用。我的搜索结果产生了以下类型的数据结构:

"results": [
{
  "created_at": "Sun, 08 Apr 2012 18:31:04 +0000",
  "entities": {
    "hashtags": [
      {
        "text": "cheeringfor",
        "indices": [
          54,
          66
        ]
      }
    ],
    "urls": [

    ],
    "user_mentions": [
      {
        "screen_name": "BenSpies11",
        "name": "Ben Spies",
        "id": 32124771,
        "id_str": "32124771",
        "indices": [
          0,
          11
        ]
      }
    ]
  },...

我正在尝试将此输出的主题标签部分包含在我的数据库表中,但我正在尝试将其保存为纯字符串。

我尝试将其转换为字符串 i:e (string)$result->hashtags 但我得到 无法转换为字符串 错误。我还尝试了 serialize() 函数,该函数有效,但是当我尝试取消序列化并取回对象时出现 php 错误。

【问题讨论】:

标签: php string json object


【解决方案1】:

首先,查找php的json_decode函数。它将您的 JSON 字符串转换为数据结构,然后您应该能够查找您的主题标签,例如:

$data = json_decode($jsonstring, true);
$hashtags = $data['results'][0]['entities']['hashtags']; // this will be an array

我没有测试过,但我认为这是正确的。如果不完全正确,您可以在此处阅读有关 json_decode() 的信息:http://php.net/manual/en/function.json-decode.php

【讨论】:

  • 您忘记了 2 参数? json_decode($jsonstring,true);
【解决方案2】:

根据您的语法,对于打印主题标签字符串,您应该编写:

$result = json_decode($your_json);
echo $result->results[0]->entities->hashtags[0]->text;

【讨论】:

    猜你喜欢
    • 2014-04-25
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    相关资源
    最近更新 更多