Get complete XML content without removing the tags

1

I need to get the complete contents of an XML file to insert it into the database. I've tried fopen but it removes the tags, and with simplexml_load_file returns array.

$ponteiro = fopen ($arquivo,"r");
while (!feof ($ponteiro)) {
$linha = fgets($ponteiro);
echo $linha."<br>";
}
fclose ($ponteiro);

So it returns only the content in text without the tags. Example of a complete XML part:

<?xml version="1.0" encoding="UTF-8"?>
<nfeProc versao="3.10" xmlns="http://www.portalfiscal.inf.br/nfe">
<NFe xmlns="http://www.portalfiscal.inf.br/nfe">
<infNFe versao="3.10" Id="NFe3516............">
<ide>
<cUF>35</cUF>
<cNF>00001623</cNF>
<natOp>VENDA DE MERCADORIA</natOp>
<indPag>1</indPag>
<mod>55</mod>
<serie>1</serie>
<nNF>1023</nNF>
<dhEmi>2016-09-02T19:57:00-03:00</dhEmi>
<dhSaiEnt>2016-09-05T19:57:00-03:00</dhSaiEnt>
<tpNF>1</tpNF>
<idDest>1</idDest>
<cMunFG>3530607</cMunFG>

I need to read an XML file from a folder and save it to MYSQL

    
asked by anonymous 04.09.2016 / 20:01

1 answer

2

The content is returning perfect with the tags, it is normal not to see them on the screen, because the browser tries to interpret as HTML.

Just a small correction, if you want to see the output from the browser:

$ponteiro = fopen( $arquivo, 'r' );
while ( !feof ($ponteiro) ) {
   $linha = fgets( $ponteiro );
   echo htmlentities( $linha )."<br>\n";
}
fclose ($ponteiro);

Note that we have not changed anything in reading, we only add htmlentities() to echo , so that tags are "escaped" correctly for HTML display.

To save to a variable or DB, you do not need htmlentities , use the data the way it is read.


Alternative

If you want to read the file in only one step:

$xml = file_get_contents( $arquivo );
echo nl2br( htmlentities( $xml ) );

This option is good when the file is not so large and can be read in memory and processed in a single step, which is often the case with XMLs.

Manual:

  

link

The nl2br is used to transform line breaks into <br> tags to make reading easier

    
04.09.2016 / 20:37