How do I read an XML file in PHP?

0

I have an invoice file in .xml that when uploading to my page in PHP, I'd like a code that displays a certain data that contains in the XML file such as the invoice number, the date of and the key.

Can anyone tell me how to read XML file with PHP?

    
asked by anonymous 31.07.2014 / 08:36

2 answers

4

You can use the 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;
    ...
}

XML:

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

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

</tag_principal>    
    
31.07.2014 / 09:50
1

That way, it's simpler. I've been using it 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);
    
17.03.2017 / 13:06