Wednesday, June 29, 2011
How to create and read JSON strings in PHP
JSON logo and PHP
PHP, 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 variable
json_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.
Subscribe to:
Post Comments (Atom)
http://eresult.co/10th-board-result-of-rajasthan-board-announced-on-18th-june-expected/
ReplyDelete