使用PHP和XMLReader解析XML [英] Parse XML with PHP and XMLReader

查看:98
本文介绍了使用PHP和XMLReader解析XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用PHP和XMLReader解析一个非常大的XML文件,但是似乎无法获得我想要的结果.基本上,我正在搜索大量信息,并且如果其中包含某个邮政编码,我想返回那一部分XML,或者继续搜索直到找到该邮政编码.本质上,我将把这个大文件分成几个小块,因此不必查看成千上万的信息组,它可能是10或20.

I've been trying to parse a very large XML file with PHP and XMLReader, but can't seem to get the results I am looking for. Basically, I'm searching a ton of information, and if a contains a certain zipcode, I'd like to return that bit of XML, or keep searching until it finds that zipcode. Essentially, I'll be breaking this big file down into only a few small chunks, so instead of having to look at thousands or millions of groups of information, it would be maybe 10's or 20's.

这里有一些我想要的XML

Here's a bit of the XML with what I'd like to

//search through xml
<lineups country="USA">
//cache TX02217 as a variable
 <headend headendId="TX02217">
//cache Grande Gables at The Terrace as a variable
  <name>Grande Gables at The Terrace</name>
//cache Grande Communications as a variable
  <mso msoId="17541">Grande Communications</mso>
  <marketIds>
   <marketId type="DMA">635</marketId>
  </marketIds>
//check to see if any of the postal codes are equal to $pc variable that will be set in the php
  <postalCodes>
   <postalCode>11111</postalCode>
   <postalCode>22222</postalCode>
   <postalCode>33333</postalCode>
   <postalCode>78746</postalCode>
  </postalCodes>
//cache Austin to a variable
  <location>Austin</location>
  <lineup>
//cache all prgSvcID's to an array i.e. 20014, 10722
   <station prgSvcId="20014">
//cache all channels to an array i.e. 002, 003  
    <chan effDate="2006-01-16" tier="1">002</chan>
   </station>
   <station prgSvcId="10722">
    <chan effDate="2006-01-16" tier="1">003</chan>
   </station>
  </lineup>
  <areasServed>
   <area>
//cache community to a variable $community   
    <community>Thorndale</community>
    <county code="45331" size="D">Milam</county>
//cache state to a variable i.e. TX
    <state>TX</state>
   </area>
   <area>
    <community>Thrall</community>
    <county code="45491" size="B">Williamson</county>
    <state>TX</state>
   </area>
  </areasServed>
 </headend>

//if any of the postal codes matched $pc 
//echo back the xml from <headend> to </headend>

//if none of the postal codes matched $pc
//clear variables and move to next <headend>

 <headend>
 etc
 etc
 etc
 </headend>
 <headend>
 etc
 etc
 etc
 </headend>
 <headend>
 etc
 etc
 etc
 </headend> 
</lineups>

PHP:

<?php
$pc = "78746";
$xmlfile="myFile.xml";
$reader = new XMLReader();
$reader->open($xmlfile); 

while ($reader->read()) { 
//search to see if groups contain $pc and echo info
}

我知道我正在使它比应有的难度更大,但是尝试操纵如此大的文件有点不知所措.感谢您的帮助.

I know I'm making this harder than it should be but am a little overwhelmed trying to manipulate such a large file. Any help is appreciated.

推荐答案

为了获得XMLReader的更多灵活性,我通常创建自己

To gain more flexibility with XMLReader I normally create myself iterators that are able to work on the XMLReader object and provide the steps I need.

从对所有节点的简单迭代开始,到可选地使用特定名称的元素上的迭代开始.我们以阅读器和元素名称作为参数,称为最后一个XMLElementIterator.

That starts with a simple iteration over all nodes over to the iteration over elements optionally with a specific name. Let's call the last one XMLElementIterator taking the reader and the element name as parameters.

然后在您的场景中,我将创建一个迭代器,该迭代器为当前元素返回一个SimpleXMLElement,仅使用<headend>元素:

In your scenario I then would create an iterator that returns a SimpleXMLElement for the current element, taking only the <headend> elements:

require('xmlreader-iterators.php'); // https://gist.github.com/hakre/5147685

class HeadendIterator extends XMLElementIterator {
    const ELEMENT_NAME = 'headend';

    public function __construct(XMLReader $reader) {
        parent::__construct($reader, self::ELEMENT_NAME);
    }

    /**
     * @return SimpleXMLElement
     */
    public function current() {
        return simplexml_load_string($this->reader->readOuterXml());
    }
}

配备了该迭代器后,剩下的工作主要是小菜一碟.首先加载10 GB的文件:

Equipped with this iterator the rest of your job is mainly a piece of cake. First load the 10 gigabyte file:

$pc      = "78746";

$xmlfile = '../data/lineups.xml';
$reader  = new XMLReader();
$reader->open($xmlfile);

然后检查<headend>元素是否包含信息,如果包含,则显示数据/XML:

And then check if the <headend> element contains the information and if so, display the data / XML:

foreach (new HeadendIterator($reader) as $headend) {
    /* @var $headend SimpleXMLElement */
    if (!$headend->xpath("/*/postalCodes/postalCode[. = '$pc']")) {
        continue;
    }

    echo 'Found, name: ', $headend->name, "\n";
    echo "==========================================\n";
    $headend->asXML('php://stdout');
}

这确实符合您要实现的目标:遍历大型文档(对内存友好),直到找到您感兴趣的元素.然后处理具体元素及其XML只要; XMLReader::readOuterXml() 在这里是很好的工具.

This does literally what you're trying to achieve: Iterate over the large document (which is memory-friendly) until you find the element(s) you're interested in. You then process on the concrete element and it's XML only; XMLReader::readOuterXml() is a fine tool here.

示例性输出:

Found, name: Grande Gables at The Terrace
==========================================
<?xml version="1.0"?>
<headend headendId="TX02217">
        <name>Grande Gables at The Terrace</name>
        <mso msoId="17541">Grande Communications</mso>
        <marketIds>
            <marketId type="DMA">635</marketId>
        </marketIds>
        <postalCodes>
            <postalCode>11111</postalCode>
            <postalCode>22222</postalCode>
            <postalCode>33333</postalCode>
            <postalCode>78746</postalCode>
        </postalCodes>
        <location>Austin</location>
        <lineup>
            <station prgSvcId="20014">
                <chan effDate="2006-01-16" tier="1">002</chan>
            </station>
            <station prgSvcId="10722">
                <chan effDate="2006-01-16" tier="1">003</chan>
            </station>
        </lineup>
        <areasServed>
            <area>
                <community>Thorndale</community>
                <county code="45331" size="D">Milam</county>
                <state>TX</state>
            </area>
            <area>
                <community>Thrall</community>
                <county code="45491" size="B">Williamson</county>
                <state>TX</state>
            </area>
        </areasServed>
    </headend>

这篇关于使用PHP和XMLReader解析XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆