Wednesday, June 29, 2011

How to create and read JSON strings in PHP

JSON logo and PHPPHP, like JavaScript, has functions that can convert variables to JSON strings and vice-versa. Let's take a look at them.Creating a JSON string from a PHP variablejson_encode() takes a PHP variable and returns a JSON string representing the variable. Here's our shopping cart example written in PHP:This produces exactly the same output as our JavaScript example — a valid JSON string representing the variable's contents:{"orderID":12345,"shopperName":"John Smith","shopperEmail":"johnsmith@example.com","contents":[{"productID":34,"productName":"SuperWidget","quantity":1},{"productID":56,"productName":"WonderWidget","quantity":3}],"orderCompleted":true}In a real-world online store, your PHP script would send this JSON string as part of the Ajax response back to the browser, where the JavaScript code would use JSON.parse() to turn the string back into a variable so it can display the cart's contents to the shopper.

3 comments:

  1. If you are going for finest contents like myself, just visit this site every
    day as it offers feature contents, thanks

    Feel free to surf to my page; sffronx

    ReplyDelete
  2. Hi! Do you use Twitter? I'd like to follow you if that would be ok.
    I'm undoubtedly enjoying your blog and look forward to
    new updates.

    Here is my website: WEight Lifting VS Cardio

    ReplyDelete
  3. What's Taking place i am new to this, I stumbled upon
    this I've found It absolutely helpful and it has helped
    me out loads. I am hoping to give a contribution &
    aid other users like its aided me. Great job.

    Feel free to visit my weblog; http://www.wellki.com/fitness/fitness-tips/3894-lifting-cardio-finding-balance

    ReplyDelete