0

please help me how to parse following JSON in PHP.

I got following JSON using PIWIK reporting api. How do I get PageTitle from following json in PHP. I tried following code for JSON parsing.

$json = '[
{
    "idSite": "1",
    "idVisit": "84",
    "visitorId": "f08dc1f2a3e1f839",
    "visitorType": "returning",
    "visitorTypeIcon": "plugins/Live/images/returningVisitor.gif",
    "visitConverted": "0",
    "visitConvertedIcon": null,
    "visitEcommerceStatus": "none",
    "visitEcommerceStatusIcon": null,
    "searches": "0",
    "events": "4",
    "actions": "9",
    "actionDetails": [
        {
            "type": "action",
            "url": "http://mywwebsiteurl.com",
            "pageTitle": "PageTitle",
            "pageIdAction": "110"
        }
    ]
}
]';

$visits = json_decode($json, true);
foreach ($visits->actionDetails as $data) { 
      echo $data->pageTitle;
}

I got following notice

Notice: Trying to get property of non-object 

How to get pageTitle from above JSON.

sathish
  • 59
  • 9
  • $visits->actionDetails['pageTitle'] should access the data. As you put true as the second parameter it returns an array not a stdClass. – Matt Burrow Jul 11 '14 at 09:17

3 Answers3

1

It should be :-

$visits = json_decode($json, true);
foreach ($visits[0]["actionDetails"] as $data) { 
      echo $data["pageTitle"];
}
Khushboo
  • 1,819
  • 1
  • 11
  • 17
0

You set second attribute to TRUE - so according to the manual. "When TRUE, returned objects will be converted into associative arrays."

Try using the array aproach

foreach ($visits['actionDetails'] as $data){
    echo $data['pageTitle'];
} 
Axel
  • 61
  • 1
  • 9
0

As documented in the manual, and mentioned by Matt, the second parameter of json_decode() controls the return type. If it is omitted or set to false (the default) then an object is returned. If it is set to true an array is returned.

Your code, json_decode($json, true);, will return an array but you then try to use the array as an object.

Community
  • 1
  • 1
timclutton
  • 12,682
  • 3
  • 33
  • 43