CSE 154

Lecture 20: A PHP JSON API

Administrivia

XKCD 1987 - Python environment

XKCD 1987 - Python environment

Pick up your tests

Homework 5 check point is due today

Creative Project 7 assigned, due Monday 5/14

Handy Chrome Extension: JSON Formatter

Q&A

Q: What is the one thing that PHP does well that JavaScript isn't well known for?

File processing

Q: From the client perspective, what is an advantage of JSON over plain text?

Easier to parse structured data, less error prone than using straight indices

Returning JSON from PHP

We use the PHP function json_encode(array) to output JSON

json_encode takes PHP arrays (including nested arrays) and generates JSON strings that can be printed

NOTE: we can also use json_decode to convert JSON strings into PHP arrays.

Example PHP code

<?php
  header("Content-Type: application/json");

  $output = array();
  $output["name"] = "Miranda";
  $output["hobbies"] = array("pottery", "softball");

  print(json_encode($output));
?>

Produces:

{
  "name":"Miranda",
  "hobbies":["pottery","softball"]
}

Examples

Other helpful PHP functions

Splitting/Joining Strings


          $array = explode(delimiter, string);
          $string = implode(delimiter, array);
          

PHP (template)


          $s = "CSE 154 A";
          $a = explode(" ", $s);     # ("CSE", "154", "A")
          $s2 = implode("...", $a);  # "CSE...154...A"
          

PHP (example)

explode and implode convert between strings and arrays.

For more complex strings, you can use regular expressions.

Example with explode


          Marty D Stepp
          Jessica K Miller
          Victoria R Kirst
          

contents of names.txt


          foreach (file("names.txt") as $name) {
            $tokens = explode(" ", $name);
            print "author: {$tokens[2]}, {$tokens[0]}\n";
          }
          

PHP

author: Stepp, Marty

author: Miller, Jessica

author: Kirst, Victoria

output

Unpacking an array: list


          list($var1, ..., $varN) = array;
          

PHP (template)


          Mr. Morton
          (206) 154 2017
          17-154-0123
          

contents of personal.txt


          list($name, $phone, $ssn) = file("personal.txt");
          ...
          list($area_code, $prefix, $suffix) = explode(" ", $phone);
          

PHP

The list function "unpacks" an array into a set of variables.

When you now a file or line's exact length/format, use file and list to unpack it