?php// 详细学习可以参考w3" /> ?php// 详细学习可以参考w3">
Home Database Mysql Tutorial XPath快速解析XML

XPath快速解析XML

Jun 07, 2016 pm 04:10 PM
xml xpath one Why use fast parse

为什么要使用XPATH,上一篇博客查询越靠近下面单词,时间会越长,超过2s就不太好了,XPAth就是用来提高解析XML速度的。还可以解析html,效率也是不错的! 分别查询下列信息 代码: vcD4KPHA+PC9wPgo8cHJlIGNsYXNzPQ=="brush:sql;">?php// 详细学习可以参考w3

为什么要使用XPATH,上一篇博客查询越靠近下面单词,时间会越长,超过2s就不太好了,XPAth就是用来提高解析XML速度的。还可以解析html,效率也是不错的!

分别查询下列信息

\

代码:喎?http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4KPHA+PC9wPgo8cHJlIGNsYXNzPQ=="brush:sql;">load('book.xml'); $xpath = new DOMXPATH($xml); /* $sql = 'xxx'; // 路径表达式 $xpath->query($sql); */ /* xpath的路径表达式如何写? xpath是从根节点到某个节点声经过的路径 */ // 查询book.xml下面的每本书的title // /bookstore/book/title /* $sql = '/bookstore/book/title'; $rs = $xpath->query($sql); print_r($rs); echo $rs->item(1)->nodeValue; */ // 查询book.xml下面book节点的下面的第2个title节点,哪来的第2个title节点? 这样写是不对的 /* $sql = '/bookstore/book/title[2]'; $rs = $xpath->query($sql); print_r($rs->length); */ // 查询bookestore下面的第2本书下面的title节点. /* $sql = '/bookstore/book[2]/title'; $rs = $xpath->query($sql); print_r($rs->item(0)->nodeValue); */ // 查询bookstore下面的book节点并且价格>40元 /* $sql = '/bookstore/book[price>40]/title'; $rs = $xpath->query($sql); echo $rs->item(0)->nodeValue; */ // 查询侠客行的价格 // /bookstore/下面的book,且title=='侠客行'的书的价格 $sql = '/bookstore/book[title="侠客行"]/price'; $rs = $xpath->query($sql); echo $rs->item(0)->nodeValue;
xpath如何不考虑路径的层次,来查询某个节点


比如我们刚才严格层次查询 /bookstore/book/title
现在我们加了一个,

<?php
$xml = new DOMDocument(&#39;1.0&#39;,&#39;utf-8&#39;);
$xml->load(&#39;book.xml&#39;);

$xpath = new DOMXPATH($xml);

$sql = &#39;/bookstore/book[last()]/title&#39;;
$rs = $xpath->query($sql);

// 只能查到书名的title
//echo $rs->item(0)->nodeValue; 


// 思考 ,如何查询所有的title,不考虑层次关系?
$sql = &#39;/title&#39;; // 这样不行,这样查的是根节点下的title,而根节点下没有title

/*
/a/b,这说明,a,b就是父子关系,而如果用/a//b,这样说明a只是b的祖先就行,忽略了层次
*/


// 不分层次,查出所有的title
/*
$sql = &#39;//title&#39;;
foreach($xpath->query($sql) as $v) {
    echo $v->nodeValue,&#39;<br />&#39;;
}
*/

/*
$sql = &#39;//title[2]&#39;; // 这样又理解成<title>a</title><title>b</title>,查询所有相邻的title节点,且第2个
foreach($xpath->query($sql) as $v) {
    echo $v->nodeValue,&#39;<br />&#39;;
}
*/
Copy after login

上面是简单应用,来改善上篇博客效率问题

<?php
// 接收单词并解析XML查询相应的单词
$word = isset($_GET[&#39;word&#39;])?trim($_GET[&#39;word&#39;]):&#39;&#39;;

if(empty($word)) {
    exit(&#39;你想查啥?&#39;);
}


// 解析XML并查询
$xml = new DOMDocument(&#39;1.0&#39;,&#39;utf-8&#39;);
$xml->load(&#39;./dict.xml&#39;);


/*
$namelist = $xml->getElementsByTagName(&#39;name&#39;);

$isfind = false;

foreach($namelist as $v) {
    if($v->nodeValue == $word) {
        //print_r($v);
        echo $word,&#39;<br />&#39;;
        echo &#39;意思:&#39;,$v->nextSibling->nodeValue,&#39;<br />&#39;;
        echo &#39;例句:&#39;,$v->nextSibling->nextSibling->nodeValue,&#39;<br />&#39;;

        $isfind = true;
        break;
    }
}

if(!$isfind) {
    echo &#39;sorry&#39;;
}
*/






// 接下来用xpath来查询词典
$xpath = new DOMXpath($xml);

// 查询/dict下的word,且name=$word的节点下面的/name节点
$sql = &#39;/dict/word[name="&#39; . $word . &#39;"]/name&#39;; 
//echo $sql;
$words = $xpath->query($sql);

if($words->length == 0) {
    echo &#39;sorry&#39;;
    exit;
}


// 查到了
$name = $words->item(0);
echo $word,&#39;<br />&#39;;
echo &#39;意思:&#39;,$name->nextSibling->nodeValue,&#39;<br />&#39;;
echo &#39;例句:&#39;,$name->nextSibling->nextSibling->nodeValue,&#39;<br />&#39;;
Copy after login

来解析一下的html

<?php
/***
====笔记部分====
xpath是根据DOM标准来查询,
html也是DOM,
也能查,岂只是xml
***/


$html = new DOMDocument(&#39;1.0&#39;,&#39;utf-8&#39;);
$html->loadhtmlfile(&#39;dict.html&#39;);


$xpath = new DOMXPATH($html);
$sql = &#39;/html/body/h2&#39;;
echo $xpath->query($sql)->item(0)->nodeValue,&#39;<br />&#39;;


// 查询id="abc"的div节点
$sql = &#39;//div[@id="abc"]&#39;;
echo $xpath->query($sql)->item(0)->nodeValue;


// 分析第2个/div/下的p下的相邻span的第2个span的内容
$sql = &#39;//div/p/span[2]&#39;;
echo $xpath->query($sql)->item(0)->nodeValue;
Copy after login


Statement of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Coinbase Exchange Login Port 2025 Coinbase Exchange Login Port 2025 Mar 21, 2025 pm 05:51 PM

Coinbase Security Login Guide: How to Avoid Phishing Sites and Scams? Phishing and scams are becoming increasingly rampant, and it is crucial to securely access the Coinbase official login portal. This article provides practical guides to help users securely find and use the latest official login portal of Coinbase to protect the security of digital assets. We will cover how to identify phishing sites, and how to log in securely through official websites, mobile apps or trusted third-party platforms, and provide suggestions for enhancing account security, such as using a strong password and enabling two-factor verification. To avoid asset losses due to incorrect login, be sure to read this article carefully!

Ouyi Exchange web version registration portal Ouyi registration portal Ouyi Exchange web version registration portal Ouyi registration portal Mar 20, 2025 pm 05:48 PM

This article details how to register an account on the official website of Ouyi OKX Exchange and start cryptocurrency trading. As the world's leading cryptocurrency exchange, Ouyi provides a wide range of trading varieties, multiple trading methods and strong security guarantees, and supports convenient withdrawal of a variety of fiat and cryptocurrencies. The article covers the search methods for Ouyi official website registration entrance, detailed registration steps (including email/mobile registration, information filling, verification code verification, etc.), as well as precautions after registration (KYC certification, security settings, etc.), and answers common questions to help novice users quickly and safely complete Ouyi account registration and start a cryptocurrency investment journey.

Ouyi okx official entrance address Ouyi official link Ouyi okx official entrance address Ouyi official link Mar 21, 2025 pm 06:09 PM

In digital currency transactions, security is crucial. Due to the prevalence of phishing, it is crucial to find Ouyi OKX official entrance address and official links. Incorrect links can lead to account theft, asset loss and identity theft. This article will provide a comprehensive guide to secure access to the Ouyi OKX official platform, helping users identify and avoid phishing websites and protecting the security of digital assets. We will introduce how to confirm the official portal of Ouyi OKX through official websites, official applications, official social media accounts and other trusted channels, and provide important security tips, such as avoiding unknown links, using strong passwords and enabling two-factor verification, to ensure your transactions are safe and reliable.

BitMEX Exchange's latest official website entrance BitMEX Exchange's latest official website entrance Mar 21, 2025 pm 06:03 PM

As a veteran cryptocurrency derivatives trading platform, the accuracy of its official website entrance is crucial. Due to rampant phishing websites, misent entry into fake websites can lead to account theft and loss of funds. This article aims to guide users to safely access the BitMEX official website, provide various methods such as trusted cryptocurrency information platforms (such as CoinMarketCap, CoinGecko), official social media, verification of existing addresses and official support channels, and emphasizes the use of security measures such as two-factor verification, regular password changes and use of security software to help users effectively avoid risks and ensure account security.

Ouyi official address Ouyi okx official entrance address Ouyi official address Ouyi okx official entrance address Mar 21, 2025 pm 06:12 PM

With the increasing popularity of digital currency trading, it is crucial to choose a safe and reliable trading platform. As the world's leading digital asset exchange, OKX's security has attracted much attention. However, many phishing websites impersonate OKX official, causing users to face the risks of account security and asset losses. This article will explain in detail how to identify and access the real Ouyi OKX official website and APP entrance to avoid phishing website traps and ensure the security of your digital assets. Through various channels such as official website verification, official app download, official social media channels, and official customer service consultation, you can effectively identify and access the OKX official platform to ensure the security of your transactions. Please be sure to carefully check the domain name, check the HTTPS protocol, and improve network security awareness.

Simulation trading software for currency speculation Simulation trading software for currency speculation Mar 19, 2025 pm 04:24 PM

Simulated transactions, also known as simulated disks or virtual transactions, are an excellent way to learn and practice cryptocurrency trading, allowing users to trade with virtual funds without taking any actual financial risks. By simulated trading, you can learn trading platform operations at zero risk, test trading strategies, practice emotional control, and become familiar with leverage use. Exchanges such as Binance, Ouyi, and Sesame Open Door all provide simulated trading platforms, and software such as TradingView and MetaTrader also provide similar functions. Although simulated trading can effectively improve trading skills, you should pay attention to the differences between them and real trading, and be cautious and do not overconfidence. This article will introduce the advantages, usage methods and precautions of simulated transactions in detail to help you stabilize the cryptocurrency market.

Ranking of the best liquid exchanges Ranking of the best liquid exchanges Mar 19, 2025 pm 04:15 PM

This article analyzes the liquidity of mainstream cryptocurrency exchanges such as Binance, Ouyi, and Sesame Open and ranks it. High liquidity is crucial for cryptocurrency trading, which means lower slippage, faster transaction speeds, and a more ideal transaction price. The article starts with indicators such as trading volume, buying and selling price spread, and order book depth. It in-depth compares the liquidity differences between the three exchanges and points out that Binance has absolute liquidity advantages, with Ouyi following closely behind, while Sesame opening needs to be improved. Finally, the article suggests that when choosing an exchange, users should consider their own needs and various factors such as liquidity and security of the exchange and make careful choices.

How to download gate exchange Download gate official app How to download gate exchange Download gate official app Mar 20, 2025 pm 05:57 PM

Gate.io Sesame Open Exchange App Download Guide: This article explains the official Gate.io Exchange App Download Method to help you trade cryptocurrency anytime, anywhere. Gate.io App has the advantages of convenience, good user experience, comprehensive functions (spot, contract, leverage, financial management, etc.) and strong security, and provides real-time market information. To ensure safety, be sure to download the App from the official website of Gate.io to avoid downloading malware. The article introduces the official website download steps and iOS and Android installation procedures in detail, and provides frequently asked questions and security suggestions to help you quickly get started with the Gate.io App and start a safe and convenient cryptocurrency trading journey.

See all articles