php生成xml文件的封装类文件-可生成带缩进格式化的xml文件及关于opcache缓存的操作小工具cachetool的使用

news2024/9/21 22:46:39

一、php生成xml文件的封装类文件-可生成带缩进格式化的xml文件

    最近因为有需要,对生成xml文件进行了一些处理,很早之前使用过SimpleXML加载接口返回的xml数据并处理,这次的使用偏向于XML文件的生成。有一个需求,生成的xml文件格式需要格式化好,xml文件在浏览器里看到的样子,一行一行内容,并且不同级别间有内容的缩进控制。这是浏览器自身的功能,实际如果不处理,生成的XML文件字符串间是连续的。例如:

<?xml version="1.0" encoding="utf-8"?>
<student><item><name>liming</name><age>21</age><sex>man</sex><note>喜欢看书</note></item><item><name>lucy</name><age>19</age><sex>woman</sex><note>喜欢看电影</note></item><item><name>lily</name><age>19</age><sex>woman</sex><note>没什么喜欢的</note></item></student>

    这样的格式在linux服务器以及在编辑器中查看都特别不好看。于是找实现这种格式化缩进的处理方法。我使用的是DomDocument来生成XML文件,DomDocument是PHP默认支持的类扩展,其中创建节点使用createElement方法,创建文本内容使用createTextNode方法,添加子节点使用appendChild方法,创建属性使用createAttribute方法。其有一项很重要的属性:

    formatOutput 布尔类型. Nicely formats output with indentation and extra space.

    在创建DomDocument类的时候设置这个属性为true,则在生成的xml文件会自动采用缩进格式,非常方便。封装的类文件及试验类的下载地址 php生成缩进格式的xml文件的封装类及测试 见本博客中的资源搜索。类代码文件Xmlmake.php代码如下:

/*
 * Note:生成XML处理类
 * Author:linge
 * Date:2017-10-23
 */

class Xmlmake
{

    //静态例属性.
    public static $document = null;
    
    //实例化类
    public function __construct($version='1.0', $charset='utf-8')
    {
        //初始化DomDocument类.并单例化
        if(!self::$document)
        {
            self::$document = new DomDocument($version, $charset);
            self::$document->formatOutput = true;
            self::$document->preserveWhiteSpace = false;
        }
    }
    
    //创建元素
    public function createElement($element)
    {
        return self::$document->createElement($element);
    }
    
    //添加子节点
    public function appendchild($child)
    {
        return self::$document->appendchild($child);
    }
    
    //返回xml字符串
    public function saveXML()
    {
        return self::$document->saveXML();
    }
    
    //添加Item
    public function createItem($item, $data, $attribute=array())
    {
        if(is_array($data))
        {
            foreach ($data as $key => $val)
            {
                //创建元素,元素名称不能以数字开头.
                is_numeric($key{0}) && exit($key. ' error:first char cannot be a number.');
                
                //添加元素
                $temp = self::$document->createElement($key);
                $item->appendchild($temp);

                //添加元素值
                $text = self::$document->createTextNode($val);
                $temp->appendchild($text);

                if(isset($attribute[$key]))
                {
                    //如果此字段存在相关属性需要设置
                    foreach($attribute[$key] as $akey => $row)
                    {
                        //创建属性节点
                        $temps = self::$document->createAttribute($akey);
                        $temp->appendchild($temps);

                        //创建属性值节点
                        $aval = self::$document->createTextNode($row);
                        $temps->appendChild($aval);
                    }
                } 
            }
        }
    }
    
    //加载Xml文件
    public function loadFile($fpath)
    {
        if(!is_file($fpath))
        {
            exit($fpath .' is a invalid file.');
        }
        
        //成功时返回 TRUE, 或者在失败时返回 FALSE
        return self::$document->load($fpath);
    }

    //保存XML至某人文件.
    public function saveFile($fpath)
    {
        //执行文件写入
        return file_put_contents($fpath, self::$document->saveXML());
    }
}

测试调用的PHP程序如下:

require 'Xmlmake.php';

$Xmlmake = new Xmlmake();
$data = array(
    
    'liming'=>array('name'=>'liming','age'=>21,'sex'=>'man','note'=>'喜欢看书'),
    'lucy'=>array('name'=>'lucy','age'=>19,'sex'=>'woman','note'=>'喜欢看电影'),
    'lily'=>array('name'=>'lily','age'=>19,'sex'=>'woman','note'=>'没什么喜欢的'),
);

$Xml = $Xmlmake->createElement('student');
$Xmlmake->appendchild($Xml);
foreach ($data as $student)
{
    $item = $Xmlmake->createElement('item');
    $Xml->appendchild($item);
    $Xmlmake->createItem($item, $student);
}

$Xmlmake->saveFile('student.xml');
echo $Xmlmake->saveXML();

//加载xml内容.
$loadRs = $Xmlmake->loadFile('student.xml');

执行后将生成格式整洁的XML文件,student.xml。格式截图如下:

二、关于opcache缓存的操作小工具cachetool的使用

     publish:October 11, 2017 -Wednesday opcache是个提升php性能的利器,但是在线上服务器真实遇到过偶尔几台服务器代码上线后,一直没有生效,查看opcache的配置也没有问题。后来没有办法,就在上线步骤中增加了重启php-fpm的操作。今天发现了一个小工具cachetool。可以方便的使用命令行清除opcache的缓存。

    当然除了重启php-fpm的进程可以清理opcache缓存外,opcache本身是支持清除缓存的。手动清理缓存涉及到的opcache函数主要为:opcache_reset()和opcache_invalidate() 。

    但是opcache_reset()是php中的函数,需要在php脚本中执行,另外当PHP以PHP-FPM的方式运行的时候,opcache的缓存是无法通过php命令进行清除的,只能通过http或cgi到php-fpm进程的方式来清除缓存。

    而opcache_invalidate 废除指定脚本缓存是使指定脚本的字节码缓存失效。可用于明确更新的代码文件列表时使用,但不方便清除整个脚本的缓存。cachetool使用起来也非常方便。如下:

#不需要安装下载下来即可使用
sudo mkdir /opt/modules/cachetool
cd /opt/modules/cachetool
#下载文件并增加可执行权限
sudo curl -sO http://gordalina.github.io/cachetool/downloads/cachetool.phar
sudo chmod +x cachetool.phar
#查看当前的opcache配置
[onlinedev@BFG-OSER-4471 ~]$ php /opt/modules/cachetool/cachetool.phar opcache:configuration --fcgi=127.0.0.1:9000
Zend OPcache 7.0.10
+---------------------------------------+----------------------+
| Directive                             | Value                |
+---------------------------------------+----------------------+
| opcache.enable                        | true                 |
| opcache.enable_cli                    | false                |
| opcache.use_cwd                       | true                 |
| opcache.validate_timestamps           | true                 |
| opcache.inherited_hack                | true                 |
| opcache.dups_fix                      | false                |
| opcache.revalidate_path               | false                |
| opcache.log_verbosity_level           | 1                    |
| opcache.memory_consumption            | 1073741824           |
| opcache.interned_strings_buffer       | 30                   |
| opcache.max_accelerated_files         | 4000                 |
| opcache.max_wasted_percentage         | 0.050000000000000003 |
| opcache.consistency_checks            | 0                    |
| opcache.force_restart_timeout         | 180                  |
| opcache.revalidate_freq               | 180                  |
| opcache.preferred_memory_model        | ''                   |
| opcache.blacklist_filename            | ''                   |
| opcache.max_file_size                 | 0                    |
| opcache.error_log                     | ''                   |
| opcache.protect_memory                | false                |
| opcache.save_comments                 | false                |
| opcache.fast_shutdown                 | true                 |
| opcache.enable_file_override          | false                |
| opcache.optimization_level            | 2147467263           |
| opcache.lockfile_path                 | '/tmp'               |
| opcache.file_cache                    | ''                   |
| opcache.file_cache_only               | false                |
| opcache.file_cache_consistency_checks | true                 |
+---------------------------------------+----------------------+
#列表查看opcache缓存的脚本
[onlinedev@BFG-OSER-4471 ~]$ php /opt/modules/cachetool/cachetool.phar opcache:status:scripts --fcgi=127.0.0.1:9000
+------+-----------+---------------------------------------------------------------------------+
| Hits | Memory    | Filename                                                                  |
+------+-----------+---------------------------------------------------------------------------+
| 8    | 4.16 KiB  | /opt/data/api/revs/r201710111538_1367/vendor/composer/autoload_static.php |
| 8    | 5.95 KiB  | /opt/data/api/revs/r201710111538_1367/www/index.php                       |
| 8    | 23.85 KiB | /opt/data/api/revs/r201710111538_1367/conf/Config.php                     |
| 8    | 848 b     | /opt/data/api/revs/r201710111538_1367/vendor/autoload.php                 |
| 8    | 84.88 KiB | /opt/data/api/revs/r201710111538_1367/lib/util/Params.php                 |
| 8    | 30.48 KiB | /opt/data/api/revs/r201710111538_1367/lib/Log.php                         |
| 8    | 6.34 KiB  | /opt/data/api/revs/r201710111538_1367/vendor/composer/autoload_real.php   |
| 8    | 51.69 KiB | /opt/data/api/revs/r201710111538_1367/app/controller/DebugController.php  |
| 8    | 6.48 KiB  | /opt/data/api/revs/r201710111538_1367/lib/Controller.php                  |
| 8    | 23.84 KiB | /opt/data/api/revs/r201710111538_1367/vendor/composer/ClassLoader.php     |
+------+-----------+---------------------------------------------------------------------------+
#查看当前的opcache缓存的统计信息
[onlinedev@BFG-OSER-4471 ~]$ php /opt/modules/cachetool/cachetool.phar opcache:status --fcgi=127.0.0.1:9000       
+----------------------+---------------------------------+
| Name                 | Value                           |
+----------------------+---------------------------------+
| Enabled              | Yes                             |
| Cache full           | No                              |
| Restart pending      | No                              |
| Restart in progress  | No                              |
| Memory used          | 66.66 MiB                       |
| Memory free          | 957.34 MiB                      |
| Memory wasted (%)    | 0 b (0%)                        |
| Strings buffer size  | 30 MiB                          |
| Strings memory used  | 221.27 KiB                      |
| Strings memory free  | 29.78 MiB                       |
| Number of strings    | 5501                            |
+----------------------+---------------------------------+
| Cached scripts       | 10                              |
| Cached keys          | 16                              |
| Max cached keys      | 7963                            |
| Start time           | Wed, 11 Oct 2017 03:30:16 +0000 |
| Last restart time    | Wed, 11 Oct 2017 07:38:20 +0000 |
| Oom restarts         | 0                               |
| Hash restarts        | 0                               |
| Manual restarts      | 4                               |
| Hits                 | 100                             |
| Misses               | 22                              |
| Blacklist misses (%) | 0 (0%)                          |
| Opcache hit rate     | 81.967213114754                 |
+----------------------+---------------------------------+
#执行清理opcache缓存
[onlinedev@BFG-OSER-4471 ~]$ php /opt/modules/cachetool/cachetool.phar opcache:reset --fcgi=127.0.0.1:9000   
#再次查看opcache缓存信息,会发现Cached scripts已被清空。                               
[onlinedev@BFG-OSER-4471 ~]$ php /opt/modules/cachetool/cachetool.phar opcache:status --fcgi=127.0.0.1:9000       
+----------------------+---------------------------------+
| Name                 | Value                           |
+----------------------+---------------------------------+
| Enabled              | Yes                             |
| Cache full           | No                              |
| Restart pending      | No                              |
| Restart in progress  | No                              |
| Memory used          | 66.43 MiB                       |
| Memory free          | 957.57 MiB                      |
| Memory wasted (%)    | 0 b (0%)                        |
| Strings buffer size  | 30 MiB                          |
| Strings memory used  | 171.92 KiB                      |
| Strings memory free  | 29.83 MiB                       |
| Number of strings    | 4283                            |
+----------------------+---------------------------------+
| Cached scripts       | 0                               |
| Cached keys          | 0                               |
| Max cached keys      | 7963                            |
| Start time           | Wed, 11 Oct 2017 03:30:16 +0000 |
| Last restart time    | Wed, 11 Oct 2017 08:36:17 +0000 |
| Oom restarts         | 0                               |
| Hash restarts        | 0                               |
| Manual restarts      | 5                               |
| Hits                 | 0                               |
| Misses               | 2                               |
| Blacklist misses (%) | 0 (0%)                          |
| Opcache hit rate     | 0                               |
+----------------------+---------------------------------+

cachetool除了可操作opcache缓存外,还可以操作apc缓存。所有的方法列表如下.
官方文档地址:http://gordalina.github.io/cachetool/
apc
  apc:bin:dump             Get a binary dump of files and user variables
  apc:bin:load             Load a binary dump into the APC file and user variables
  apc:cache:clear          Clears APC cache (user, system or all)
  apc:cache:info           Shows APC user & system cache information
  apc:cache:info:file      Shows APC file cache information
  apc:key:delete           Deletes an APC key
  apc:key:exists           Checks if an APC key exists
  apc:key:fetch            Shows the content of an APC key
  apc:key:store            Store an APC key with given value
  apc:sma:info             Show APC shared memory allocation information
opcache
  opcache:configuration    Get configuration information about the cache
  opcache:reset            Resets the contents of the opcode cache
  opcache:status           Show summary information about the opcode cache
  opcache:status:scripts   Show scripts in the opcode cache

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1977222.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【保姆级讲解下AI绘画自动生成器有哪些?】

&#x1f3a5;博主&#xff1a;程序员不想YY啊 &#x1f4ab;CSDN优质创作者&#xff0c;CSDN实力新星&#xff0c;CSDN博客专家 &#x1f917;点赞&#x1f388;收藏⭐再看&#x1f4ab;养成习惯 ✨希望本文对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出…

CICD流水线

一、CICD流水线简介 CICD概念 CI/CD流水线是现代软件开发的一个核心概念&#xff0c;它涉及自动化和管理软件从开发到部署的整个生命周期 概念定义 具体有三点&#xff1a;持续集成、持续交付、持续部署 流水线组成为&#xff1a;代码提交、测试、构建、部署、结果通知 二…

营销型豆浆机料理机网站模板/EyouCMS营销型类企业模板

营销型豆浆机料理机网站模板&#xff0c;EyouCMS营销型类企业模板。模板自带eyoucms内核&#xff0c;无需再下载eyou系统&#xff0c;原创设计、手工书写DIVCSS&#xff0c;完美兼容IE7、Firefox、Chrome、360浏览器等&#xff1b;主流浏览器&#xff1b;结构容易优化&#xff…

雨量气象站:实时、准确地监测并记录降水情况

在自然界的水循环中&#xff0c;雨&#xff0c;作为天空与大地的信使&#xff0c;不仅滋养了万物&#xff0c;也影响着人类社会的方方面面。为了更准确地监测和预测降水情况&#xff0c;雨量气象站应运而生&#xff0c;成为了现代气象观测体系中重要的一环。 雨量气象站&#x…

FFmpeg源码:av_reduce函数分析

AVRational结构体和其相关的函数分析&#xff1a; FFmpeg有理数相关的源码&#xff1a;AVRational结构体和其相关的函数分析 FFmpeg源码&#xff1a;av_reduce函数分析 一、av_reduce函数的声明 av_reduce函数声明在FFmpeg源码&#xff08;本文演示用的FFmpeg源码版本为7.0…

P10477 题解

题目传送门 题目传送门&#xff08;洛谷&#xff09; Step1 理解题意 一共有 T T T 组数据有一个地铁&#xff0c;有一个中心车站&#xff08;即为根&#xff09;&#xff0c;有一个人从中心车站出发。对于每组数据&#xff0c;给定两个同样长度的01串 s 1 s_1 s1​ , s …

五、MYSQL企业常用架构与调优经验理论篇

&#x1f33b;&#x1f33b; 目录 一、选择 PerconaServer、MariaDB 还是 MYSQL二、常用的 MYSQL 调优策略三、MYSOL 常见的应用架构分享四、MYSOL 经典应用架构 注&#xff1a;全是理论干货&#xff0c;没有实战&#xff0c;想看实战的绕路哦&#xff01;&#xff01;&#xf…

ScriptEcho:AI赋能的前端代码生成神器

ScriptEcho&#xff1a;AI赋能的前端代码生成神器 在前端开发中&#xff0c;如果你总是觉得写代码太费时费力&#xff0c;那么 ScriptEcho 将成为你的救星。这个 AI 代码生成平台不仅能帮你省下大量时间&#xff0c;还能让你轻松愉快地写出生产级代码。本文将带你了解 ScriptEc…

Java中spring boot validation 自定义注解使用

创建一个注解 Target({ElementType.FIELD})//需要写注解的三三个要素 Retention(RUNTIME) Documented Constraint(validatedBy {IsSystemYesNoVaildation.class})//绑定 在这里会报错 你需要去实现 public interface IsSystemYesNo {String message() default "数据字典&…

【Python实战】如何优雅地实现文字 二维码检测?

前几篇&#xff0c;和大家分享了如何通过 Python 和相关库&#xff0c;自动化处理 PDF 文档&#xff0c;提高办公效率。 【Python实战】自动化处理 PDF 文档&#xff0c;完美实现 WPS 会员功能【Python实战】如何优雅地实现 PDF 去水印&#xff1f;【Python实战】一键生成 PDF…

自媒体新闻资讯类网站模板/EyouCMS自媒体资讯类网站模板

自媒体新闻资讯类网站模板&#xff0c;EyouCMS自媒体资讯类网站模板。模板自带eyoucms内核&#xff0c;无需再下载eyou系统&#xff0c;原创设计、手工书写DIVCSS&#xff0c;完美兼容IE7、Firefox、Chrome、360浏览器等&#xff1b;主流浏览器&#xff1b;结构容易优化&#x…

U460909 [BCSP小高2024T4]先序遍历/小羊的晚餐 题解

Part.1 有关本题 本蒟蒻想起这道巧妙 又毒瘤 的题&#xff0c;到处搜寻提交窗口。好不容易找到窗口&#xff0c;有花了 3 h 3h 3h 的时间调题。 本蒟蒻为了悲剧不再发生&#xff0c;于是出了这道题&#xff0c;有写下了这篇题解以供后人。 以下的题解默认以阅读过原题。 P…

数学建模--禁忌搜索

目录 算法基本原理 关键要素 应用实例 实现细节 python代码示例 总结 禁忌搜索算法在解决哪些具体类型的组合优化问题中最有效&#xff1f; 禁忌搜索算法的邻域结构设计有哪些最佳实践或案例研究&#xff1f; 如何动态更新禁忌表以提高禁忌搜索算法的效率和性能&#…

FPGA开发——数码管数字时钟的设计

一、概述 数码管数字时钟的基本原理是通过内部的计时电路&#xff08;如晶振、分频器、计数器等&#xff09;产生一个稳定的时钟信号&#xff0c;该信号经过处理后被转换为小时、分钟和秒的时间信息。这些信息随后被发送到数码管显示模块&#xff0c;通过控制数码管中不同LED段…

Android读取拨号记录功能

Android读取拨号记录功能 Android读取拨号记录功能 首先会检测应用是否有读取拨号记录的权限 MainActivity.java public class MainActivity extends AppCompatActivity {private ListView listCalls;private List<Map<String, Object>> mapList;private static f…

有界,可积,存在原函数和连续的关系

目录 1.可积和有界的关系 2.连续和可积的关系 3.连续和存在原函数的关系 4.可积和存在原函数没有关系 1.可积和有界的关系 可积必有界&#xff0c;有界不一定可积&#xff0c;反例可以举狄利克雷函数 2.连续和可积的关系 f(x)连续&#xff0c;则一定可积&#xff0c;可积不…

Mac安装nvm以及配置环境变量

安装nvm brew install nvm安装成功后会出现这样一段话: Add the following to your shell profile e.g. ~/.profile or ~/.zshrc:export NVM_DIR"$HOME/.nvm"[ -s "/opt/homebrew/opt/nvm/nvm.sh" ] && \. "/opt/homebrew/opt/nvm/nvm.sh&q…

Substance Painter界面介绍

1 界面介绍01_哔哩哔哩_bilibili 界面 选择texture 笔刷参数 分成不同的材质球 选择不同工具跟着变动 p4

STL序列式容器之list的使用及实现

std::list 和 std::vector 是两种不同的数据结构&#xff0c;std::vector 是基于数组的动态数组&#xff0c;而 std::list 是基于双向链表的数据结构。list适用于需要在序列中频繁执行插入和删除操作的场景。 1.list的特性 双向链表&#xff1a; list是一个双向链表&#xff…

R 语言学习教程,从入门到精通,R的安装与环境的配置(3)

1、R 基础语法 一门新的语言学习一般是从输出 “Hello, World!” 程序开始&#xff0c;R 语言的 “Hello, World!” 程序代码如下&#xff1a; myString <- "Hello, World!" print ( myString )以上示例将字符串 “Hello, World!” 赋值给 myString 变量&#x…