Heim  >  Artikel  >  php教程  >  PHP使用xmllint命令处理xml与html的方法

PHP使用xmllint命令处理xml与html的方法

WBOY
WBOYOriginal
2016-06-06 20:15:54846Durchsuche

这篇文章主要介绍了PHP使用xmllint命令处理xml与html的方法,较为详细的讲述了使用xmllint工具的各种命令处理XML文件与html的方法,是非常具有实用价值的技巧,需要

本文实例讲述了html">PHPhtml">使用xmllint命令处理xml与html的方法。分享给大家供大家参考。具体分析如下:

xmllint是一个很方便的处理及验证xml、处理html的工具,linux下只要安装libxml2就可以使用这个命令。首先看下其结合--html 、--xpath参数处理html时的例子:

示例如下:

复制代码 代码如下:

curl /ip/?q=8.8.8.8 2>/dev/null | xmllint --html --xpath "//ul[@id='csstb']" - 2>/dev/null | sed -e 's/]*>//g'


上例中主要是通过在123cha上查询的IP地址的归属情况后,通过提取结果(ul#csstb),只获取文本部分的内容。上面的脚本语句执行后的结果如下:

[您的查询]:8.8.8.8
本站主数据:
美国
本站辅数据:Google Public DNS提供:hypo
美国 Google免费的Google Public DNS提供:zwstar参考数据一:美国
参考数据二:美国

下面再结合示例看下其他主要参数的用法。
1、 --format
此参数用于格式化xml,使其具有良好的可读性。
假设有xml(person.xml)内容如下:

复制代码 代码如下:

ball30male


执行如下操作后其输出为更易读的xml格式:

复制代码 代码如下:

#xmllint --format person.xml

   
      ball
      30
      male
   


2、 --noblanks
与--format相反,有时为了节省传输量,我们希望去掉xml中的空白,这时我们可以使用--noblanks命令。
假设xml(person.xml)内容如下

复制代码 代码如下:


   
      ball
      30
      male
   


执行该参数操作后,其输出结果为:

复制代码 代码如下:

#xmllint --noblanks person.xml

    ball30male


3、--schema
使用scheam验证xml文件的正确性(XML Schema 是基于 XML 的 DTD 替代者)
假设有xml文件(person.xml)和scheam文件(person.xsd)文件,内容分别如下
person.xml

复制代码 代码如下:


   
      ball
      30
      male
   


person.xsd

复制代码 代码如下:


   
     
     
     
       
         
           
           
         

       

     

     
       
         
           
           
           
         

       

     

   


按如下命令执行后的结果是:

复制代码 代码如下:

#xmllint --schema person.xsd person.xml

   
      ball
      30
      male
   

person.xml validates 
注:默认情况下,验证后会输出验证的文件内容,可以使用 --noout选项去掉此输出,这样我们可以只得到最后的验证结果。

复制代码 代码如下:

#xmllint --noout --schema person.xsd person.xml


person.xml validates 
下面我们改动person.xml,使这份文件age字段和sex都是不符合xsd定义的。

复制代码 代码如下:

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn