Recently the company to do an API interface, the output format to have JSON and XML format, in PHP, input JSON directly json_encode can, but the output XML does not provide functions, so decided to write a.
Formatoutput = true;} /** * Convert an array to XML * @param array $array array to convert * @param string $rootName to Node name * @param string $version version number * @param string $ Encodingxml encoded * * @return string */public static function parse ($array, $rootName = ' root ', $version = ' 1.0 ', $encoding = ' UTF-8 ') {self::init ($version, $encoding);//Convert $node = Self::convert ($array, $rootName); Self:: $doc->appendchild ($ node); return self:: $doc->savexml ();} /** * Recursive conversion * * @param array $array arrays * @param string $nodeName node name * * @return Object (domelement) */private static func tion convert ($array, $nodeName) {if (!is_array ($array)) return false;//Create parent node $node = Self::createnode ($nodeName);// Loop array foreach ($array as $key + $value) {$element = Self::createnode ($key);//If it is not an array, create the value of the node if (!is_array ($value)) {$ Element->appendchild (Self::createvalue ($value)); $node->appendchild ($element);} else {//If it is an array, then recursive $node->appendchild (Self::convert ($value, $key, $element));}} return $node;} private static function CreateNode ($name) {$nodE = null;//If it is a string, create the node if (!is_numeric ($name)) {$node = self:: $doc->createelement ($name);} else {//If it is a number, The default item node is created $node = self:: $doc->createelement (' item ');} return $node;} /** * Create Text node * * @param string | | bool | | Integer $value * * @return object (Domtext | | Domcdatasection); */private static function CreateValue ($value) {$textNode = null;//if the bool type is converted to a string if (true = = = $value | | false = = = $value) {$textNode = self:: $doc->createtextnode ($value? ' True ': ' false ');} else {//If the HTML tag is included, create a CDATA node if (Strpos ($value, ' < ') >-1) {$textNode = self:: $doc->createcdatasection ($value );} else {$textNode = self:: $doc->createtextnode ($value);}} return $textNode;}}
http://www.bkjia.com/PHPjc/477156.html www.bkjia.com true http://www.bkjia.com/PHPjc/477156.html techarticle recently the company to do an API interface, output format to have JSON and XML format, in PHP, input JSON directly json_encode can, but the output XML does not provide functions, so decided to write a ...