用原生php封装json类,xml类
时间: 2023-12-10 20:54:41 浏览: 31
以下是使用原生PHP封装的JSON类和XML类的示例代码:
JSON类:
```
class JSON {
public static function encode($data) {
return json_encode($data);
}
public static function decode($json, $assoc = false) {
return json_decode($json, $assoc);
}
}
```
XML类:
```
class XML {
public static function encode($data, $root = 'data') {
$xml = new SimpleXMLElement('<'.$root.'/>');
self::arrayToXML($data, $xml);
return $xml->asXML();
}
private static function arrayToXML($data, &$xml) {
foreach($data as $key => $value) {
if(is_array($value)) {
if(is_numeric($key)) {
$key = 'item'.$key;
}
$subnode = $xml->addChild($key);
self::arrayToXML($value, $subnode);
} else {
$xml->addChild("$key", htmlspecialchars("$value"));
}
}
}
public static function decode($xml) {
return json_decode(json_encode(simplexml_load_string($xml)), true);
}
}
```
使用示例:
```
// JSON编码
$data = array('name' => 'John', 'age' => 30);
$json = JSON::encode($data);
echo $json; // {"name":"John","age":30}
// JSON解码
$data = JSON::decode($json);
print_r($data); // Array ( [name] => John [age] => 30 )
// XML编码
$data = array('name' => 'John', 'age' => 30);
$xml = XML::encode($data);
echo $xml; // <data><name>John</name><age>30</age></data>
// XML解码
$data = XML::decode($xml);
print_r($data); // Array ( [name] => John [age] => 30 )
```