When doing data interfaces, we typically get Third-party data interfaces or provide data interfaces to third parties, which are typically transmitted in XML or JSON format, and this article describes how to use PHP to generate XML format data for Third-party calls and how to obtain XML data from third parties.
PHP generates interface communication data
?
| 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 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 5 86 87 88 89 90 91 92 93 |
/** * Generate Interface Data Format/class response{/** * [Show in integrated way output DATA] * @param [int] $code [status code] * @param [string] $message [hint info] * param array $data [data] * @param [string] $type [Type] * @return [string] [return value]/public static function show ($code, $messag E, $data = Array (), $type = ') {if (!is_numeric ($code)) {return ';} $result = Array (' Code ' => $code, ' message ' => $message, ' data ' => $data); if ($type = = ' json ') {return Self::json ($code, $message, $data);} ElseIf ($type = = ' xml ') {return self::xml ($code, $message, $data);} else{//todo}}/** * [JSON output data by JSON] * @param [int] $code [status code] * @param [string] $message [hint info] * @param [array] $d ATA [Data] * @return [string] [return value] */public static function json ($code, $message, $data = Array ()) {if (!is_numeric ($code)) {return ';} $result = Array (' Code ' => $code, ' message ' => $message, ' data ' => $data); $result = Json_encode ($result); return $result; } /** * [XML generates data in XML format] * @param [int] $code [status code] * @param [string] $message [hint] * @param array $data [data] * @return [string] [return value] */public static function XML ($code, $message, $data = a Rray ()) {if (!is_numeric ($code)) {return ';} $result = Array (' Code ' => $code, ' message ' => $message, ' data ' => $DATA); Header ("Content-type:text/xml"); $xml = "<?xml version= ' 1.0 ' encoding= ' UTF-8 '" >n "; $xml. = "<root>n"; $xml. = Self::xmltoencode ($data); $xml. = "</root>"; return $xml; } public static function Xmltoencode ($data) {$xml = '; foreach ($data as $key => $value) {if (Is_numeric ($key)) { $attr = "id= ' {$key} '"; $key = "Item"; $xml. = "<{$key} {$attr}>n"; $xml. = Is_array ($value)? Self::xmltoencode ($value): "{$value}n"; $xml. = "</{$key}>n"; return $xml; } //Test $grade = Array ("Score" => Array ("70.0"), "name" => Array ("Zhang San", "Li Si", "Wang Wu "," Zhao Liu "," Tianqi "); $response = new response (); $result = $response:: Show (' Success ', $grade, ' json '); Print_r ($result); |
The above is the entire contents of this article, I hope you can enjoy.