0

i need to extract data from this array of objects

{
    "data": [
        {
            "id": "136104923104306",
            "from": {
                "name": "GetWith.It",
                "category": "Website",
                "id": "136132969751208"
            },
            "message": "Do u know y **LOVE IS BLIND**\nbcoz..\n''ur mom started to love u before seeing ur face''....!",
            "updated_time": "2010-10-05T13:41:42+0000",
            "comments": {
                "data": [
                    {
                        "id": "136104923104306_1075253",
                        "from": {
                            "name": "Hressence Ec",
                            "id": "1464305271"
                        },
                        "message": "this I would agree..love is surely blind..",
                        "created_time": "2010-10-12T01:40:47+0000",
                    }
                ]
            }
        }

My current code:

$data=json_decode(file_get_contents('https://myurl/where/this/data/is'));
foreach($data as $dts){
echo "$dts->message";
};

i need to extract the comments .. and when i try

foreach($data->comments->data as $dts){
echo "$dts->message";
};

it returns null! help please

3
  • I don't think your data is "json-valid" btw. Try validating it on jsonlint.com Commented Dec 30, 2010 at 11:33
  • 2
    NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit. pt2.php.net/json_decode Commented Dec 30, 2010 at 11:35
  • Btw: You should "take a look" at your $data with var_export, print_r or whatever, to "see" the problem. You could also work with a debugger :) Commented Dec 30, 2010 at 11:36

2 Answers 2

1

Your $data is actually an object with a data property that is an array containing another object with the comments object you are looking for. So:

foreach ($data->data as $item) {
    foreach ($item->comments->data as $comment) {
        echo $comment->message;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I suggest you transform it into an associative array:

$data=json_decode(file_get_contents('https://myurl/where/this/data/is'), true);

and have a look at the structure.

I think your loop must look like this:

foreach($data['data'] as $dts) {
    echo $dts['message'];
}

Update: Although I was able to fix the JSON (at least it seems to be good now) json_decode still returns null. No clue way. First make sure your JSON string is valid!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.