duanjing9739 2010-12-03 14:46
浏览 59
已采纳

将值从XML检索到PHP数组中

I've written a small function to read an XML file with simpleXML and used Pear Benchmark Iterate to time it. I've read that simpleXML and DOM puts the entire XML file into memory which can create a lot of overhead on files of a large size.

The function below is a relatively small size and I'm only pulling 10 values from the XML file.

Iterations of the function below (xml filesize: 200kb) takes 2.5 seconds to complete on average.

Can anyone suggest a solution with PHP XMLparser, a related class, or perhaps some other efficient way to parse xml into an array?

SimpleXML version

function getItems($file_id, $item_count=5)
{
    switch ($file_id)
    {
        case '1':
        $file = "http://xml_file.xml";

        if ($xml = simplexml_load_file($file)) 
        {
            $i=0;
            foreach ($xml->info as $info) 
            {
                if ($i < $item_count)
                {
                    $var[] = array(
                        "id"  =>  (string)$info->id,
                        "name" => (string)$info->name); 
                }
                $i++;   
            }
            return $var;
        }
    }
}
  • 写回答

1条回答 默认 最新

  • doushou9028 2010-12-03 15:08
    关注

    The XML Parser module may be the better option that doesn't require some external library, although it requires a bit of a mind shift. They payback is that the data is never loaded into memory in its entirety.

    In a nutshell, you will need to treat the XML document in a tree descending matter and keep a journal of your location in the tree as opening and closing tags are reported to you through handlers.

    It may seem daunting that this module is not OO, but xml_set_object alleviates this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算