在laravel中解析XML文件

问题描述 投票:0回答:2

我想从我的计算机中选择一个XML文件进行解析。表单有效,我可以使用Input :: file('file');功能。但是,我希望通过仅将其作为临时文件上载来解析此文档。当我想解析它时,我得到如下错误:“无法从字符串解析”。似乎解析器找不到该文件。我尝试了两个解析器:SimpleXML和XMLParser(来自管弦乐)。

public function uploadFile(Request $ file){
$data =Input::file('file');
$informationdata = array('file' => $data);
$rules = array(
    'file' => 'required|mimes:xml|Max:10000000',
    );
    $validator=  Validator::make($informationdata, $rules);
    if($validator->fails()){
        echo 'the file has not the correct extension';
    } else{
        XmlParser::load($data->getRealPath());
    }

我还试图在存储文件后解析它。

private function store($data){
    $destinationPath = public_path('uploads\\');
    $fileName = $data->getClientOriginalName();
    $data->move($destinationPath,$fileName);
    $xml = simplexml_load_file($destinationPath.$fileName);
    }

在此先感谢您的帮助。

php xml parsing laravel-5.2
2个回答
0
投票

当你说“解析”是什么意思?查找节点?删除节点?添加节点?或者只读节点?

因为你可以找到和阅读SimpleXMLElement类,但如果你想添加或删除我建议你使用DomDocument。

使用SimpleXMLElement,构造将是:

$xml = new SimpleXMLElement($destinationPath.$fileName, null, true);

而DomDocument将是:

$xml = new DomDocument('1.0', 'utf-8'); // Or the right version and encoding of your xml file
$xml->load($destinationPath.$fileName);

创建对象后,您无法处理所有文档。


0
投票

不知道是否要在计算机上验证某些现有的xml文件,或者想要实现用户上传任何xml文件并编写一些逻辑来应对此任务的能力。但是,这不是重点。

我建议你使用内置的PHP核心simplexml_load_file()函数来帮助我完成这个项目。因为你永远不会让Laravel将xml解析为一些体面的可下班数组或对象,以通过Request $ file injections等工作。这对于使用html-forms或json很好,而不是使用xml或其他格式。

这就是为什么你应该使用对象,这将是(例如)这样的代码的结果:

$xml_object = simplexml_load_file($request->file('action')->getRealPath());

然后你需要自己验证每个xml节点和字段,编写一些逻辑,因为你失去了使用内置到Laravel Illuminate \ Http \ Request validate()方法的可能性。

© www.soinside.com 2019 - 2024. All rights reserved.