JSON对象作为PHP字符串

问题描述:

可能重复:
Convert a JSON into a UTF-8 stringJSON对象作为PHP字符串

我上缓存一些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但我得到不能转换为字符串错误 我也试过连载()函数,它的工作,但得到了PHP的错误,当我试图取消序列化并返回对象。

我将不胜感激任何帮助。

+0

刚刚发现http://stackoverflow.com/问题/ 4409039 /转换-A-JSON - 到 - 一个UTF-8串。这个职位应该关闭 – sisko 2012-04-10 15:06:29

+0

不,因为这是另一个问题。 – Bergi 2012-04-10 15:13:59

首先,查看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

+1

你忘了2参数? json_decode($ jsonstring,真正的); – 2012-04-10 15:30:32

与你的语法据,打印包括hashtag字符串,你应该写:

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