Book Image

Building a Web Application with PHP and MariaDB: A Reference Guide

By : Sai S Sriparasa
Book Image

Building a Web Application with PHP and MariaDB: A Reference Guide

By: Sai S Sriparasa

Overview of this book

Table of Contents (17 chapters)
Building a Web Application with PHP and MariaDB: A Reference Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Generating JSON feeds


In the last section, we used PHP's SimplXMLElement class to generate our XML feeds. In this section, we will use PHP's json_encode function to generate our JSON feed. Building a JSON feed is very simple when compared to building the XML feed. JSON is a very popular data exchange format and is considered lightweight when compared to XML, as shown in the following code snippet, present in the controllers/api.php file:

private function _generateJSON($root, $data){
  header("HTTP/1.1 200 OK");
  header("Content-Type: application/json");
  echo json_encode(array($root=>$data));
}

In this snippet, we begin by building our _generateJSON method that will expect the name of the endpoint and the data that was fetched by the get action. Now, let's modify the get action to use the _generateJSON method, as shown in the following code snippet:

if(strlen($method)>0){
  $data = $this->model->$method();

  if(is_array($data) && count($data) >0){
    $this->_generateJSON...