How do I read an XML file in PHP?

Asked

Viewed 231 times

0

I have a receipt file on .xml that when uploading to my PHP page, I would like a code that shows up a certain data that contains in the XML file such as the invoice number, the date of issue and the key.

Could someone tell me how I read XML file with PHP?

  • Welcome to Stackoverflow! Asking a tutorial leaves the question outside the scope of SOPT. Try to be more objective in the question, for example: "How do I read an XML file in PHP?"

2 answers

4


You can use PHP DOM:

$dom = new DomDocument();

$dom->load( $file_name )

$tuas_tags = $this->dom->getElementsByTagName( 'tag_principal' );

foreach ( $tuas_tags as $tua_tag )
{
    $nomeTAG = $tua_tag->getElementsByTagName( 'tag_nome'      );
    $nome    = $nomeTAG->item( 0 )->nodeValue;
    ...
}

the XML:

<tag_principal>
     <tag_nome>Jorge B</tag_nome>
     ...

</tag_principal>
<tag_principal>
     <tag_nome>Cachuera</tag_nome>
     ...

</tag_principal>    
  • Very thx apparently is this right there I need it. I will test as soon as I get home and then I give a feedback here on topic

1

This way down is simpler.
I’ve been wearing this since 2010.

// Directory for file storing filesystem path
$d = dirname(__FILE__);
$upload_dir = "$d/nfs";

$c = $n = $u = $y = $s = $v = '';

$file = $upload_dir.'/tmp/'.md5(rand()).".test"; // file name
move_uploaded_file($_FILES['file']['tmp_name'], "$file");    

// Carrega o XML e o XSL
$xml = simplexml_load_file("$file");
$c = $xml->getName();

switch ($c) {
    case "GerarNfseResposta": //PB
        $n = $xml->children('nfse', TRUE); //Namesspace as Prefix
        $n = $n->ListaNfse->CompNfse->Nfse->InfNfse;
        $u = $n->PrestadorServico->IdentificacaoPrestador->CpfCnpj;
        $u = ($u->Cpf?$u->Cpf:$u->Cnpj);
        $s = $n->Numero+0;
        $c = $n->DataEmissao;
        $y = substr($c, 0, 4)+0;
        $c = date("Y-m-d H:i:s", strtotime($c));
        $v = $n->CodigoVerificacao;
        echo "<!-- u:$u y:$y s:$s v:$v c:$c -->";
        break;
    case "CompNfse": //BH
        $n = $xml->children('http://www.abrasf.org.br/nfse.xsd'); //Namesspace only
        $n = $n->Nfse->InfNfse;
        $u = $n->PrestadorServico->IdentificacaoPrestador;
        $u = ($u->Cpf?$u->Cpf:$u->Cnpj);
        $s = substr($n->Numero, 4)+0;
        $c = $n->DataEmissao;
        $y = substr($c, 0, 4)+0;
        $c = date("Y-m-d H:i:s", strtotime($c));
        $v = $n->CodigoVerificacao;
        echo "<!-- u:$u y:$y s:$s v:$v c:$c -->";
        break;
    case 2:
        break;
}

unset($xml);

Browser other questions tagged

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