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

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

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

示例如下:

代码如下:

curl http://www.bitsCN.com /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.bitsCN.com
 

 
 
  
   
    
     
     
      
       
        
       

      

     

     
     
     
    

    
   

  

 

 

 
 
 
  
 

 


使用 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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.