php使用函數方式讀取XML檔案的例子

來源:互聯網
上載者:User
  • else
  • ";
  • echo "";
  • }

  • function content($x,$content){

  • echo $content;
  • }

  • $printerror=false;

  • $xmlfile="user.xml";

  • //第二步 讀取資料
  • $fp=fopen($xmlfile,"r");

  • while(!feof($fp)){

  • $data=fread($fp,1024);
  • //開始解析
  • if(!xml_parse($xml,$data)){
  • $printerror=true;
  • }
  • }

  • //關閉檔案

  • fclose($fp);
  • if($printerror){
  • $row=xml_get_current_line_number($xml);
  • $col=xml_get_current_column_number($xml);
  • $errormess=xml_error_string(xml_get_error_code($xml));
  • echo "在檔案{$xmlfile}中,[{$row}行,{$col}列]:{$errormess}.";
  • }
  • //關閉解析器
  • xml_parser_free($xml);
  • ?>

  • 複製代碼
    1. //第一步 建立解析器 xml_parser_create(編碼);

    2. $xml = xml_parser_create('utf-8');
    3. //xml_parser_set_option — 為指定 XML 解析進行選項設定
    4. //xml_parser_set_option($xml,XML_OPTION_CASE_FOLDING,false); false原樣輸出
    5. //註冊事件,將遇到開始和結束表計時使用什麼函數
    6. xml_set_element_handler($xml,"starttag","endtag");

    7. xml_set_character_data_handler($xml,"content");

    8. function starttag($x,$tagName,$args){

    9. if($tagName=="USERS")
    10. echo "
    11. echo "
    12. }else
    13. "; ";
    14. echo "
    15. {$tagName}";
    16. else if($tagName == "USER"){
    17. echo "
    18. {$args['ID']} ";
    19. }

    20. function endtag($x,$tagName){

    21. if($tagName=="USERS")
    22. echo "
    23. ";
    24. else if($tagName == "USER")
    25. echo "
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.