简体   繁体   中英

Need Help in reading an XML file with PHP

hi i want to read the below file using php. the file is of very big size (in GBs). Please help me out as i dont knw much about this.

Here is the file

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Articles>
        <Article>
            <header>info about article  </header>

        <metadata>


                    <dc:title>title here</dc:title>
                    <dc:author>author 1</dc:author>
                    <dc:author>author 2</dc:author>
                    <dc:author>author 3</dc:author>
                    <dc:author>author n</dc:author>

                    <dc:subject>subject here</dc:subject>


            </metadata>
        </Article>

        <resume> resume infor </resume>
        </Articles>

如果文件很大,你可能需要使用XMLReader来避免内存不足而不是SimpleXML。

www.w3schools.com/PHP/php_xml_simplexml.asp

Try reading this page. Its of great help.

Update Found this snippet on StackOverflow.com's posts:

<?php

class SimpleDMOZParser
{
    protected $_stack = array();
    protected $_file = "";
    protected $_parser = null;

    protected $_currentId = "";
    protected $_current = "";

    public function __construct($file)
    {
        $this->_file = $file;

        $this->_parser = xml_parser_create("UTF-8");
        xml_set_object($this->_parser, $this);
        xml_set_element_handler($this->_parser, "startTag", "endTag");
    }

    public function startTag($parser, $name, $attribs)
    {
        array_push($this->_stack, $this->_current);

        if ($name == "TOPIC" && count($attribs)) {
            $this->_currentId = $attribs["R:ID"];
        }

        if ($name == "LINK" && strpos($this->_currentId, "Top/Home/Consumer_Information/Electronics/") === 0) {
            echo $attribs["R:RESOURCE"] . "\n";
        }

        $this->_current = $name;
    }

    public function endTag($parser, $name)
    {
        $this->_current = array_pop($this->_stack);
    }

    public function parse()
    {
        $fh = fopen($this->_file, "r");
        if (!$fh) {
            die("Epic fail!\n");
        }

        while (!feof($fh)) {
            $data = fread($fh, 4096);
            xml_parse($this->_parser, $data, feof($fh));
        }
    }
}

$parser = new SimpleDMOZParser("content.rdf.u8");
$parser->parse();

PHP的SimpleXML是一个很好的起点

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM