You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

90 lines
2.5 KiB

  1. <?php
  2. namespace Kuxin\Helper;
  3. /**
  4. * Class Xml
  5. *
  6. * @package Kuxin\Helper
  7. * @author Pakey <pakey@qq.com>
  8. */
  9. class Xml
  10. {
  11. /**
  12. * @param $data
  13. * @param string $root
  14. * @param string $attr
  15. * @param bool $forceCdata
  16. * @param string $encoding
  17. * @return mixed
  18. */
  19. public static function encode($data, $root = 'xml', $attr = '', $forceCdata = false, $encoding = 'utf-8')
  20. {
  21. if (is_array($attr)) {
  22. $_attr = [];
  23. foreach ($attr as $key => $value) {
  24. $_attr[] = "{$key}=\"{$value}\"";
  25. }
  26. $attr = implode(' ', $_attr);
  27. }
  28. $attr = trim($attr);
  29. $attr = empty($attr) ? '' : " {$attr}";
  30. $xml = "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>" . PHP_EOL;
  31. $xml .= "<{$root}{$attr}>" . PHP_EOL;
  32. $xml .= self::dataToXml($data, '', $forceCdata);
  33. $xml .= "</{$root}>";
  34. return $xml;
  35. }
  36. /**
  37. * 数据XML编码
  38. *
  39. * @param mixed $data 数据
  40. * @param bool $forceCdata
  41. * @param string $parentkey
  42. * @return string
  43. */
  44. protected static function dataToXml($data, $parentkey = '', $forceCdata = false)
  45. {
  46. $xml = '';
  47. foreach ($data as $key => $val) {
  48. if (is_numeric($key)) {
  49. $key = $parentkey;
  50. } elseif (substr($key, 0, 10) == '__string__') {
  51. $xml .= $val;
  52. continue;
  53. }
  54. $key = $key ? $key : 'xmldata';
  55. $xml .= "<{$key}>";
  56. if (is_array($val) || is_object($val)) {
  57. $len = strlen("<{$key}>");
  58. $con = self::dataToXml($val, $key, $forceCdata);
  59. if (strpos($con, "<{$key}>") === 0) {
  60. $con = substr(trim($con), $len, -($len + 1));
  61. }
  62. $xml .= $con;
  63. } elseif ($forceCdata || strlen($val) > 150 || preg_match('{[<>&\'|"]+}', $val)) {
  64. $xml .= '<![CDATA[' . $val . ']]>';
  65. } else {
  66. $xml .= $val;
  67. }
  68. $xml .= "</{$key}>" . PHP_EOL;
  69. }
  70. return $xml;
  71. }
  72. public static function decode($con)
  73. {
  74. if (!$con) {
  75. return [];
  76. }
  77. if ($con{0} == '<') {
  78. $con = simplexml_load_string($con, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
  79. } else {
  80. $con = simplexml_load_file($con, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
  81. }
  82. return Json::decode(Json::encode($con), true);
  83. }
  84. }