用php讀寫xml檔案

來源:互聯網
上載者:User

php中對xml讀取的相關函數的介紹:

--------------------------------------------------------------------------------

對象 XML解析函數 描述
元素 xml_set_element_handler() 元素的開始和結束
字元資料 xml_set_character_data_handler() 字元資料的開始
外部實體 xml_set_external_entity_ref_handler() 外部實體出現
未解析外部實體 xml_set_unparsed_entity_decl_handler() 未解析的外部實體出現
處理指示 xml_set_processing_instruction_handler() 處理指示的出現
記法聲明 xml_set_notation_decl_handler() 記法聲明的出現
預設 xml_set_default_handler() 其它沒有指定處理函數的事件

--------------------------------------------------------------------------------

下面就給大家舉一個小小的例子用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>

這個程式的結果如下:

--------------------------------------------------------------------------------

名字:張三 職位:經理
名字:李四 職位:助理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.