1 | <?php |
---|
2 | |
---|
3 | include_once('collection.php'); |
---|
4 | |
---|
5 | class Hypermedia { |
---|
6 | |
---|
7 | public $collection; |
---|
8 | public $version = '0.1'; |
---|
9 | |
---|
10 | function setCollection($collection) { |
---|
11 | $this->collection = $collection; |
---|
12 | } |
---|
13 | |
---|
14 | function getCollection() { |
---|
15 | return $this->collection; |
---|
16 | } |
---|
17 | |
---|
18 | function getHypermeida($accept = 'json') { |
---|
19 | |
---|
20 | $data = get_object_vars($this); |
---|
21 | |
---|
22 | switch ($accept) { |
---|
23 | case 'json': |
---|
24 | return json_encode($data); |
---|
25 | break; |
---|
26 | case 'xml': |
---|
27 | return $this->generateValidXmlFromArray($data); |
---|
28 | default : |
---|
29 | return json_encode($data); |
---|
30 | } |
---|
31 | } |
---|
32 | |
---|
33 | // functions adopted from http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/ |
---|
34 | |
---|
35 | function generateValidXmlFromObj(stdClass $obj, $node_block = 'nodes', $node_name = 'node') { |
---|
36 | $arr = get_object_vars($obj); |
---|
37 | return self::generateValidXmlFromArray($arr, $node_block, $node_name); |
---|
38 | } |
---|
39 | |
---|
40 | function generateValidXmlFromArray($array, $node_block = 'nodes', $node_name = 'node') { |
---|
41 | $xml = '<?xml version="1.0" encoding="UTF-8" ?>'; |
---|
42 | |
---|
43 | $xml .= '<' . $node_block . '>'; |
---|
44 | $xml .= self::generateXmlFromArray($array, $node_name); |
---|
45 | $xml .= '</' . $node_block . '>'; |
---|
46 | |
---|
47 | return $xml; |
---|
48 | } |
---|
49 | |
---|
50 | function generateXmlFromArray($array, $node_name) { |
---|
51 | $xml = ''; |
---|
52 | |
---|
53 | if (is_array($array) || is_object($array)) { |
---|
54 | foreach ($array as $key => $value) { |
---|
55 | if (is_numeric($key)) { |
---|
56 | $key = $node_name; |
---|
57 | } |
---|
58 | |
---|
59 | $xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>'; |
---|
60 | } |
---|
61 | } else { |
---|
62 | $xml = htmlspecialchars($array, ENT_QUOTES); |
---|
63 | } |
---|
64 | |
---|
65 | return $xml; |
---|
66 | } |
---|
67 | |
---|
68 | } |
---|
69 | |
---|
70 | ?> |
---|