search
HomeBackend DevelopmentPHP TutorialPHP读取xml方法介绍_PHP

一,什么是xml,xml有什么用途

  XML(Extensible Markup Language)即可扩展标记语言,它与HTML一样,都是SGML(Standard Generalized Markup Language,标准通用标记语言)。Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具。扩展标记语言XML是一种简单的数据存储语言,使用一系列简单的标记描述数据,而这些标记可以用方便的方式建立,虽然XML占用的空间比二进制数据要占用更多的空间,但XML极其简单易于掌握和使用。
XML的用途很多,可以用来存储数据,可以用来做数据交换,为很多种应用软件提示数据等等。
二,php读取xml的方法
  xml源文件
复制代码 代码如下:



张映

28


tank

28




  1)DOMDocument读取xml
复制代码 代码如下:
$doc = new DOMDocument();
$doc->load('person.xml'); //读取xml文件
$humans = $doc->getElementsByTagName( "humans" ); //取得humans标签的对象数组
foreach( $humans as $human )
{
$names = $human->getElementsByTagName( "name" ); //取得name的标签的对象数组
$name = $names->item(0)->nodeValue; //取得node中的值,如
$sexs = $human->getElementsByTagName( "sex" );
$sex = $sexs->item(0)->nodeValue;
$olds = $human->getElementsByTagName( "old" );
$old = $olds->item(0)->nodeValue;
echo "$name - $sex - $old\n";
}
?>


  2)simplexml读取xml
复制代码 代码如下:
$xml_array=simplexml_load_file('person.xml'); //将XML中的数据,读取到数组对象中
foreach($xml_array as $tmp){
echo $tmp->name."-".$tmp->sex."-".$tmp->old."
";
}
?>


  3)用php正则表达式来记取数据
复制代码 代码如下:
$xml = "";
$f = fopen('person.xml', 'r');
while( $data = fread( $f, 4096 ) ) {
$xml .= $data;
}
fclose( $f );
// 上面读取数据
preg_match_all( "/\(.*?)\/s", $xml, $humans ); //匹配最外层标签里面的内容
foreach( $humans[1] as $k=>$human )
{
preg_match_all( "/\(.*?)\/", $human, $name ); //匹配出名字
preg_match_all( "/\(.*?)\/", $human, $sex ); //匹配出性别
preg_match_all( "/\(.*?)\/", $human, $old ); //匹配出年龄
}
foreach($name[1] as $key=>$val){
echo $val." - ".$sex[$key][1]." - ".$old[$key][1]."
" ;
}
?>


  4)xmlreader来读取xml数据
复制代码 代码如下:
$reader = new XMLReader();
$reader->open('person.xml'); //读取xml数据
$i=1;
while ($reader->read()) { //是否读取
if ($reader->nodeType == XMLReader::TEXT) { //判断node类型
if($i%3){
echo $reader->value; //取得node的值
}else{
echo $reader->value."
" ;
}
$i++;
}
}
?>


  三,小结
  读取xml的方法很多,简单举几个。上面四种方法都是可以把标签中的数据读出来,张映.但是他们的测重点不同,前三种方法的读取xml的function的设计重点,是为了读取标签中的值,相当于jquery中的text()方法,而xmlreader呢他就不太一样,他的重点不在读取标签中的值,而读取标签的属性,把要传送的数据,都放在属性中(不过我上面写的那个方法还是取标签中的值,因为xml文件已经给定了,我就不想在搞xml文件出来了)。
  举个例子解释一下,
  
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

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

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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),