php教程 php手册 php读取xml文件的三种实现方法

php读取xml文件的三种实现方法

May 25, 2016 pm 04:42 PM

文章介绍了三种方式来读取xml文件分别是new DOMDocument(),正则解析xml,用parser函数来读取xml数据,这些方法都是可行的,但第一种和最后一种要好一些.

new DOMDocument()实例代码如下:

<?php
$doc = new DOMDocument();
$doc->load(&#39;books.xml&#39;);
$books = $doc->getElementsByTagName("book");
foreach ($books as $book) {
    $authors = $book->getElementsByTagName("author");
    $author = $authors->item(0)->nodeValue;
    $publishers = $book->getElementsByTagName("publisher");
    $publisher = $publishers->item(0)->nodeValue;
    $titles = $book->getElementsByTagName("title");
    $title = $titles->item(0)->nodeValue;
    echo "$title - $author - $publisher/n";
}
?>
로그인 후 복사

正则解析,代码如下:

<?php
$xml = "";
$f = fopen(&#39;books.xml&#39;, &#39;r&#39;);
while ($data = fread($f, 4096)) {
    $xml.= $data;
}
fclose($f);
preg_match_all("//<book/>(.*?)/<//book/>/s", $xml, $bookblocks);
foreach ($bookblocks[1] as $block) {
    preg_match_all("//<author/>(.*?)/<//author/>/", $block, $author);
    preg_match_all("//<title/>(.*?)/<//title/>/", $block, $title);
    preg_match_all("//<publisher/>(.*?)/<//publisher/>/", $block, $publisher);
    echo ($title[1][0] . " - " . $author[1][0] . " - " . $publisher[1][0] . "/n");
}
?>
로그인 후 복사

books.xml文件如下:

<books> 
  <book> 
  <author>Jack Herrington</author> 
  <title>PHP Hacks</title> 
  <publisher>O&#39;Reilly</publisher> 
  </book> 
  <book> 
  <author>Jack Herrington</author> 
  <title>Podcasting Hacks</title> 
  <publisher>O&#39;Reilly</publisher> 
  </book> 
</books>
로그인 후 복사

下面就给大家举一个小小的例子用parser函数来读取xml数据,代码如下:

<?php
$parser = xml_parser_create(); //创建一个parser编辑器
xml_set_element_handler($parser, "startElement", "endElement"); //设立标签触发时的相应函数 这里分别为startElement和endElenment
xml_set_character_data_handler($parser, "characterData"); //设立数据读取时的相应函数
$xml_file = "1.xml"; //指定所要读取的xml文件,可以是url
$filehandler = fopen($xml_file, "r"); //打开文件
while ($data = fread($filehandler, 4096)) {
    xml_parse($parser, $data, feof($filehandler));
} //每次取出4096个字节进行处理
fclose($filehandler);
xml_parser_free($parser); //关闭和释放parser解析器
$name = false;
$position = false;
function startElement($parser_instance, $element_name, $attrs) //起始标签事件的函数
{
    global $name, $position;
    if ($element_name == "NAME") {
        $name = true;
        $position = false;
        echo "名字:";
    }
    if ($element_name == "POSITION") {
        $name = false;
        $position = true;
        echo "职位:";
    }
}
function characterData($parser_instance, $xml_data) //读取数据时的函数
{
    global $name, $position;
    if ($position) echo $xml_data . "<br>";
    if ($name) echo $xml_data . "<br>";
}
function endElement($parser_instance, $element_name) //结束标签事件的函数
{
    global $name, $position;
    $name = false;
    $position = false;
}
?>
로그인 후 복사

xml文件代码如下:

<?xml version="1.0" 
<employees> 
<employee> 
<name>张三</name> 
<position age="45">经理</position> 
</employee> 
<employees> 
<employee> 
<name>李四</name> 
<position age="45">助理</position> 
</employee> 
</employees>
로그인 후 복사

parser是php内置的一个用来处理xml的解析器,它的工作由三个事件组成:起始标签、 读取数据、结束标签.

也就是说在对xml进行处理的时候每当遇到起始标签、数据和结束标签的时候函数会做相应的动作来完成对xml数据的转换.


教程链接:

随意转载~但请保留教程地址★

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)