Mar 17, 2010

Parsing JSON response with PHP

We are currently trying to tie in the Yelp API into our group project so I thought I would post what we have learned in trying to parse the JSON response. Since JSON is the only response method that Yelp offers, it was imperative that we figure it out. First, the proxy part is the same, meaning that I obtained the response the same way that I did with all of my XML responses. To do this I use this but of code:




After that I use the json_decode() function to convert the data into a searchable format:


NOTE: One nice trick that I learned is to do a var_dump() of the data variable to your output destination. What this does is essentially show you the structure of the JSON response so that you can see the hierarchy of tags. This is similar to just putting your XML URL into firefox in order to see the layout. To do this I use the following snippet of code:



The output will look like this:



After that it is just a matter of figuring out which items you want to retrieve and then grabbing that information. Yelp puts everything under the heading of businesses, which means that I use the following code to access the elements:



So here is the output on the site:


4 comments:

  1. Adam, you always seem to make things look so easy. For us beginners we need these kind of examples to help us figure out whats going on. I still am working to parse my data and get it to display, but its nice to have these posts to refer to. I hope that one day I will gain the experience that you have.

    ReplyDelete
  2. Thank you for explaining how to parse JSON. Some APIs don't play nice when trying to parse XML.

    ReplyDelete
  3. Yes, thank you very much for explaining how to parse JSON. I am going to try it with my fanfeedr that I was trying a couple of weeks ago. After I try it, I will blog about what happened.

    ReplyDelete
  4. Thanks a lot..Helped in my project as well !!

    ReplyDelete