代码之家  ›  专栏  ›  技术社区  ›  Shail Paras

php xmlreader未返回完整数据

  •  1
  • Shail Paras  · 技术社区  · 8 年前

    你好,我正在尝试从XML文件中获取所有数据,所以我使用了xmltoassoc函数。它适用于5MB文件,但不适用于9mb以上的文件。

    这是我的代码: 我修改了这个函数以获得json代码,

    function xml2assoc($xml, $name)
    {
        $tree = null;
        while($xml->read()) 
        {
            if($xml->nodeType == XMLReader::END_ELEMENT)
            {
                return $tree;
            }        
            else if($xml->nodeType == XMLReader::ELEMENT)
            {
                $node = array();            
                if($xml->hasAttributes)
                {
                    $attributes = array();
                    while($xml->moveToNextAttribute()) 
                    {
                        $attributes[$xml->name] = $xml->value;
                    }
                }
    
                if(!$xml->isEmptyElement)
                {               
                    $childs = xml2assoc($xml, $node['tag']);
                    if(isset($childs['text']))
                    {
                       $tree = $childs;
                    } else {
                       $tree['text'] = $childs[0];
                    }
                }
            }        
            else if($xml->nodeType == XMLReader::TEXT)
            {   
                if(isset($xmlArr['text']))
                {
                   $tree = $xmlArr;
                } else {
                   $tree['text'] = $xmlArr[0];
                }            
            }
        }
        return $tree; 
    }
    

    我使用此函数通过传递URL返回JSON。

    function PARSE_XML_JSON($url)
    {
        $text = "";
        $xml = new XMLReader();
        $xml->open($url); 
        $assoc = xml2assoc($xml, "root"); 
        $xml->close();
        if(isset($assoc['text']))
        {
            $text = $assoc['text'];
        }
        //StoreInTxtFile($text);
        return $text;
    }
    

    我还尝试通过以下方式将数据保存到文件中:

    function StoreInTxtFile($data)
    {
        $myFile = 'jsonfile-'.time().'.txt';
        $fh = fopen($myFile, 'w') or die("can't open file");
        fwrite($fh, $data);
        fclose($fh);
    }
    

    请告诉我我错过了什么。 谢谢

    1 回复  |  直到 8 年前
        1
  •  1
  •   NID    8 年前

    使用 LIBXML_PARSEHUGE

            $xml = new XMLReader();
            $xml->open($url, NULL, LIBXML_PARSEHUGE);