search
HomeBackend DevelopmentPHP TutorialPHP使用xmllint命令处理xml与html的方法_php技巧

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

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

示例如下:

复制代码 代码如下:
curl http://www.jb51.net /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定义的。
复制代码 代码如下:
#xmllint --noout --schema person.xsd person.xml
person.xml:4: element age: Schemas validity error : Element 'age': 'not age' is not a valid value of the atomic type 'xs:integer'.
person.xml:5: element sex: Schemas validity error : Element 'sex': [facet 'enumeration'] The value 'test' is not an element of the set {'male', 'female'}.
person.xml:5: element sex: Schemas validity error : Element 'sex': 'test' is not a valid value of the local atomic type.
person.xml fails to validate

可以看到xmllint成功的报出了错误!

4、 关于--schema的输出

在讲输出之前先看下面一个场景,假如你想通过php执行xmllint然后拿到返回结果,你的代码通常应该是这个样子valid.php

复制代码 代码如下:
$command = "xmllint --noout --schema person.xsd person.xml";
exec($command, $output, $retval);
//出错时返回值不为0
if ($retval != 0){
    var_dump($output);
}
else{
    echo "yeah!";
}

我们保持上文中person.xml的错误。

执行此代码,你会发现,你拿到的output不是错误,而是array(0) {}, amazing!
为什么会这样呢?

因为xmllint --schema,如果验证出错误,错误信息并不是通过标准输出(stdout)显示的,而是通过标准错误(stderr)进行显示的。

而exec的output参数拿到的,只能是标准输出(stdout)显示的内容。
所以,为了拿到出错信息,我们需要将标准错误重定向到标准输出,对应修改代码:

复制代码 代码如下:
$command = "xmllint --noout --schema person.xsd person.xml 2>$1";

再次执行valid.php,错误信息顺利拿到!

例子如下:
首先建立一份 xml 文档,命名为 po.xml,其内容如下:

复制代码 代码如下:


   
        Alice Smith
        123 Maple Street
        Mill Valley
        CA
        90952
   

   
        Robert Smith
        8 Oak Avenue
        Old Town
        PA
        95819
   

    Hurry, my lawn is going wild!
   
       
            Lawnmower
            1
            148.95
            Confirm this is electric
       

       
            Baby Monitor
            1
            39.98
            1999-05-21
       

   


然后为 po.xml 写的 schema 文件,取名为 po.xsd,内容如下:
复制代码 代码如下:

 
 
   Purchase order schema for Example.com.
   Copyright 2000 Example.com. All rights reserved.
 

 

 
 
 
 
  
  
  
  
 

 
 

 
 
  
  
  
  
  
 

  www.jb51.net
 

 
 
  
   
    
     
     
      
       
        
       

      

     

     
     
     
    

    
   

  

 

 

 
 
 
  
 

 


使用 xmllint 对 po.xml 文件进行校验:
复制代码 代码如下:
$ xmllint   -schema po.xsd po.xml
如果无出错信息,就说明校验通过了。

希望本文所述对大家的PHP程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft