🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ <?php /* * 1. 创建xml数据并写入xml文件 * 2. 读取xml文件为数组 * 写入的数据只能是“一维数组”,如果是多维,请转为1为数组 */ $XML = new XML(); $dataArr = [ 'id' => 1, 'name' => 'test', 'key' => 'this is key', 'content' => 'this is content' ]; //创建xml文件 $xml_data = $XML->xmlData($dataArr); //根据xml文件读取xml数据为数组 $getXmlData = $XML->xml_data_load(); var_dump($getXmlData); class XML { const FILEDIR = __DIR__.DIRECTORY_SEPARATOR."test.xml"; /** * @param $dataArr 数组数据 * @param $is_file 是否创建xml文件 * * @return void */ public function xmlData($dataArr = [], $is_file = true) { $xml = new SimpleXMLExtended('<?xml version="1.0" encoding="UTF-8"?><item></item>'); $xml->addChild('pubDate', date('Y-m-d H:i:s')); foreach ($dataArr as $key => $v) { $note = $xml->addChild($key); $note->addCData($v); } $data = @$xml->asXML(); $xml = $this->formatXmlString($data); if ($is_file) { $status = $this->XMLsave($xml, self::FILEDIR); if ($status) { print_r("创建成功<br>"); } else { print_r("创失败啦<br>"); } } else { var_dump($xml); } } /** * 保存为xml文件 * * @param $xml * * @return bool */ private function XMLsave($xml) { $data = $this->exec_filter('xmlsave', $xml); $success = file_put_contents(self::FILEDIR, $data); // LOCK_EX ? return $success && chmod(self::FILEDIR, 0755); } /** * 根据xml文件,解析xml数据为数组 * @return array|mixed|stdClass|void */ public function xml_data_load() { $file = self::FILEDIR; if (file_exists($file)) { $data = $this->getXML($file); $xml_json = json_encode($data);//转换为json数据 $xml_array = json_decode($xml_json, true);//转换成数组 return $xml_array; } } /** * 删除xml文件 * * @param $id * * @return true */ public function delete_file($file) { $filepath = GSDATAPAGESPATH; if ($this->filepath_is_safe($file, $filepath)) { unlink($file); } return true; } function formatXmlString($data) { if (gettype($data) === 'object') { $data = $data->asXML(); } $dom = new DOMDocument('1.0'); $dom->preserveWhiteSpace = false; $dom->formatOutput = true; $dom->loadXML($data); $ret = $dom->saveXML(); return $ret; } function getXML($file) { $xml = @file_get_contents($file); if ($xml) { $data = simplexml_load_string($xml, 'SimpleXMLExtended', LIBXML_NOCDATA); return $data; } } function exec_filter($script, $data = []) { return $data; } function filepath_is_safe($path, $pathmatch, $subdir = true) { $realpath = realpath($path); $realpathmatch = realpath($pathmatch); if ($subdir) { return strpos(dirname($realpath), $realpathmatch) === 0; } return dirname($realpath) == $realpathmatch; } } class SimpleXMLExtended extends SimpleXMLElement { public function addCData($cdata_text) { $node = dom_import_simplexml($this); $no = $node->ownerDocument; $node->appendChild($no->createCDATASection($cdata_text)); } } ~~~