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: 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
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.
<?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"]
}
$array = explode(delimiter, string);
$string = implode(delimiter, array);
$s = "CSE 154 A";
$a = explode(" ", $s); # ("CSE", "154", "A")
$s2 = implode("...", $a); # "CSE...154...A"
explode
and implode
convert between strings and arrays.
For more complex strings, you can use regular expressions.
explode
Marty D Stepp
Jessica K Miller
Victoria R Kirst
foreach (file("names.txt") as $name) {
$tokens = explode(" ", $name);
print "author: {$tokens[2]}, {$tokens[0]}\n";
}
author: Stepp, Marty
author: Miller, Jessica
author: Kirst, Victoria
list
list($var1, ..., $varN) = array;
Mr. Morton
(206) 154 2017
17-154-0123
list($name, $phone, $ssn) = file("personal.txt");
...
list($area_code, $prefix, $suffix) = explode(" ", $phone);
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