-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathch8p1JSON.php
More file actions
87 lines (83 loc) · 2.15 KB
/
ch8p1JSON.php
File metadata and controls
87 lines (83 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
include_once('generalIncludes.php');
echo '<input id="chapter" type="hidden" value="8">';
echo '<h2>Chapter 8 Data Formats and Types - Paragraph paragraph JSON encoding data</h2>';
showcode(<<<'CODE'
$array = ["foo", "bar", 9=>'bdaz'];
$string = json_encode($array);
echo $string ."\n";
var_dump($string);
CODE
);
showcode(<<<'CODE'
$array = ["one" => "foo", "two" => "bar", "three" => "baz"];
echo json_encode($array);
CODE
);
echo '<h3>Listing 8.1: JSON options</h3>';
echo 'Try removing any of the parameters, or $options from the call. Or the key from the data which might return a array, if JSON_FORCE_OBJECT is not set:';
showcode(<<<'CODE'
$array = [
"name" => "Davey Shafik",
"age" => "30",
];
$options = JSON_PRETTY_PRINT |
JSON_NUMERIC_CHECK |
JSON_FORCE_OBJECT;
echo json_encode($array, $options);
CODE
);
echo 'Try removing any of the parameters:';
showcode(<<<'CODE'
$array = [
"tags" => "These are tags <> <b> etc",
"ampersand" => "This is a ampersand &",
"apostrophe" => "This is a apostrophe ''",
"quote" => "This is a quote \"",
];
$options =
JSON_HEX_TAG |
JSON_HEX_AMP |
JSON_HEX_APOS |
JSON_HEX_QUOT;
echo json_encode($array, $options);
CODE
);
echo '<h3>Listing 8.2: Implementing JsonSerializable</h3>';
showcode(<<<'CODE'
class User implements JsonSerializable
{
public $first_name;
public $last_name;
public $email;
public $password;
public function jsonSerialize() {
return [
"name" => $this->first_name
. ' ' . $this->last_name,
"email_hash" => md5($this->email),
];
}
}
$me = new User();
$me->first_name = 'Davey';
echo json_encode($me);
$davey = [
'first_name' => 'Davey',
'last_name' => 'Shafik',
'email' => 'davey@example.com',
'password' => '$2y$10$TeDnXI3Oz0P5Bgv9sADE9.v7SIGESaoWhFe28ctpVsU47f/BAtFFa'
];
echo json_encode($davey);
CODE
);
echo '<h2>Chapter 8 Data Formats and Types - Paragraph paragraph JSON decoding data</h2>';
echo 'Decode into an object or into an array.';
showcode(<<<'CODE'
$json = '{ "name": "Davey Shafik", "age": 30 }';
$data = json_decode($json);
print_r($data);
$data = json_decode($json, true);
print_r($data);
CODE
);