Get complete XML content without removing tags

Asked

Viewed 981 times

1

I need to get the full contents of an XML file to insert it into the database. I have 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 text content without the tags. Full XML part example:

<?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 its contents to MYSQL

  • 1

    [SOLVED] Thanks @Bacco entered the return in the database and recorded correctly, if print in the browser it removes the tags even.

  • In your case, this solution here is more practical, to read everything at once: http://php.net/manual/en/function.file-get-contents.php

1 answer

4


The content is returning perfect with the tags, it is normal not to be able 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 by browser:

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

Note that we do not change anything in reading, just add a htmlentities() in the 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 as it is read.


Alternative

If you want to read the file in 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 usually the case of Xmls.

Handbook:

http://php.net/manual/en/function.file-get-contents.php

The nl2br serves to turn line breaks into tags <br>, for easy reading

Browser other questions tagged

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