Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

How to Use PHP to Return the Date in JSON Format

JavaScript Object Notation (JSON) is a means to exchange data between web services in a simple and succint manner, without all of the overhead of XML. JSON is a great way to integrate a web service with JavaScript because JSON can be easily parsed by JavaScript code. Even better, PHP includes native functions to both create and read JSON.

These functions, json_encode() and json_decode(), make it easy to work with JSON and create JSON web services from PHP.

A simple way to get your feet wet with web services is to return a date in JSON format. Here's how you can do that:

  1. Open your text editor or programming IDE and create a new empty file.

    image0.jpg
  2. Place the following code within the file:

    <?php
    $header = "Content-Type: application/json";
    header($header);
     
    $date = date("M d, Y");
    print json_encode($date);
    ?>
  3. Save the file as date.php in your web server's document root.

    image1.jpg
  4. View the page in your web browser at http://localhost/date.php.

    You should see a page like that shown here (though the date will probably be different).

    image2.jpg

    The page contains a JSON-encoded date. This date could then be parsed with JavaScript or even consumed from another PHP program. Note the use of application./json as an HTTP header. This is critically important to inform the calling program (whether JavaScript or PHP) that it should expect to receive a JSON response as opposed to HTML, XML, or another type of response.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!