How to read XML with PHP

Asked

Viewed 176 times

-1

Hello I’m starting to learn PHP, and I created an HTML input that receives an XML file that should be read in PHP but I’m having difficulties, I’m using the simplexml_load_file more when I call the xml data does not return anything just like in this print: inserir a descrição da imagem aqui

I wonder how I can solve?

My code: (index.php)

<html>
<body>
<form action="teste.php" method="post" enctype="multipart/form-data">
    <label for="myfile">coloque o arquivo XML:</label>
    <input type="file" id="myfile2" name="myfile2"><br><br>
    <input type="submit" value="Submit">
</form>

(php test.)

<html>
<body>
<?php
 $myfile2 = $_FILES['myfile2']['tmp_name'];
 $dados_xml = simplexml_load_file($myfile2);
 echo $dados_xml
?>
</body>
</html>
  • you want to show the xml on the screen?

  • that same the xml content, actually only a few fields but for starters yes

1 answer

1


The code is wrong, because, will not show the result on screen, and the function simplexml_load_file returns an object of type Simplexmlelement that is misunderstood by the browser and what is needed is the simple content of that and change the page head to Context-type: text/xml, then open the file with the function fopen read your content with fread and close your pointer with fclose and finally send the content that the browser will understand because of the configuration of your Content-type, example:

function load_xml()
{
  header("Content-type: text/xml");
  $filename = $_FILES['myfile2']['tmp_name'];
  $handle = fopen($filename, "r");
  $conteudo = fread($handle, filesize($filename));
  fclose($handle);
  return $conteudo;
}

echo load_xml();
  • 1

    Thank you for clarifying

Browser other questions tagged

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