Read XML received from ajax - PHP

Asked

Viewed 154 times

3

In php using the command var_dump($_FILES ['filexml']); I receive the following values from ajax

array(5) {
  ["name"]=>
  string(56) "nomeficticio.xml"
  ["type"]=>
  string(8) "text/xml"
  ["tmp_name"]=>
  string(14) "/tmp/phpoqnomeficticio"
  ["error"]=>
  int(0)
  ["size"]=>
  int(16536)
}

Through this data, how can I read this XML file? with PHP I even tried to use the command simplexml_load_file($_FILES['filexml']); but made the following mistake:

simplexml_load_file() expects Parameter 1 to be a Valid path, array Given

  • You are passing the entire array as parameter, while you need the path of a file to read. I think, in your case, simplexml_load_file($_FILES['filexml']['name']) is the most appropriate, as long as the path in this array field is the correct one

  • @Caiofelipepera Hmmm, I need to upload first so I can read the XML? or I can read the xml without necessarily uploading it (save to some directory)

  • The guys already got the jump right there, hahaha. But the thing was kind of

2 answers

3


The array already tells you where the file is located. Just open it:

simplexml_load_file($_FILES['filexml']['tmp_name']);

However, it is not recommended to treat a file that is in a temporary directory, as the OS itself can clean this directory from time to time. You’d rather move him before that:

$basename = basename($_FILES['filexml']['tmp_name']);
move_uploaded_file($_FILES['filexml']['tmp_name'], __DIR__ . $basename);
simplexml_load_file( __DIR__ . $basename);
  • Simmm, that’s right Worked perfectly, thanks for the tip.

  • The two answers were great, but this one answered me also another small question that had here

3

You only need to use tmp_name instead of name. Take an example:

<?php
if(isset($_FILES['input_file'])){
    $xml = simplexml_load_file($_FILES['input_file']["tmp_name"]);
    echo '<pre>';
    var_dump($xml);
    echo '</pre>';
}
?>
<form class="frm" method="post" enctype="multipart/form-data" novalidate="novalidate">
    <input type="file" name="input_file"/>
    <input type="submit" value="Enviar"/>
</form>

I hope I’ve helped!

If it works out, I’d be happy to give me an upvote and choose my answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.