Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

formigoni

[Resolvido] Lendo Cabeçalho

Recommended Posts

Olá bom dia,

 

Como posso ler uma informação que está no cabeçalho de um XML de NFe?

Preciso pegar o Id e a Versão que estão no "infNFE", quarta linha abaixo

O trecho do XML é esse:

 

   <?xml version="1.0" encoding="UTF-8" ?> 
- <nfeProc versao="1.10" xmlns="http://www.portalfiscal.inf.br/nfe">
- <NFe xmlns="http://www.portalfiscal.inf.br/nfe">
- <infNFe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Id="NFe41100878956968004332550050000004171101465722" versao="1.10">

O meu PHP está assim:

 

 <?php
/*------------------------------------------------------------
Data - 02/09/2010
Função - Ler e Salvar informações do XML no banco de dados
--------------------------------------------------------------
*/

	header("Content-Type: text/html; charset=ISO8859-1");
		if (!function_exists("GetSQLValueString")) {
		function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
		{
		  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
		
		  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
		
		  switch ($theType) {
			case "text":
			  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
			  break;    
			case "long":
			case "int":
			  $theValue = ($theValue != "") ? intval($theValue) : "NULL";
			  break;
			case "double":
			  $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
			  break;
			case "date":
			  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
			  break;
			case "defined":
			  $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
			  break;
		  }
		  return $theValue;
		}
		}			
	
		require_once("../db/conexao.php");

			// diretorio onde estao os arquivos - criado a pasta NFEArquivo temporariamente
			$dir = "NFEletronica/";
		
			// esse seria o "handler" do diretório
			$dh = opendir($dir);
			
			// loop que busca todos os arquivos até que não encontre mais nada
			while (false !== ($filename = readdir($dh))) {		
				// verificando se o arquivo é .xml
				if (substr($filename,-4) == ".xml") {	
					
					// Composição do caminho
					$arquivo = "NFEletronica/".$filename;
						
					// converter XML em objetos 			
					$xml = simplexml_load_file($arquivo);					
						
					// print_r($xml);	
														
					// Leitura do ramo NFe
					$Id 		   = utf8_decode($xml->NFe->infNFe->Id);
					$Versao		   = utf8_decode($xml->NFe->infNFe->versao);
					// identificação
					$nfNumeroNF	   = utf8_decode($xml->NFe->infNFe->ide->nNF);
					$nfDataEmissao = utf8_decode($xml->NFe->infNFe->ide->dEmi);
					// Emitente					
					$nfCPFCNPJEmit = utf8_decode($xml->NFe->infNFe->emit->CNPJ);
					$nfNomeEmit	   = utf8_decode($xml->NFe->infNFe->emit->xNome);	
					// Destinatário
					$nfCPFCNPJDest = utf8_decode($xml->NFe->infNFe->dest->CPF);
					$nfNomeDest	   = utf8_decode($xml->NFe->infNFe->dest->xNome);	
				
					mysql_select_db($database_conexao, $conexao);
					$query_BuscaNFE = "SELECT * FROM NFEArquivo WHERE IdNFEArquivo = '$Id'";
					$BuscaNFE = mysql_query($query_BuscaNFE, $conexao) or die(mysql_error());
					$row_BuscaNFE = mysql_fetch_assoc($BuscaNFE);
					$totalRows_BuscaNFE = mysql_num_rows($BuscaNFE);
															
					if($totalRows_BuscaNFE == 0){
						// Insere as informações no banco de dados
						mysql_select_db($database_conexao, $conexao);
						$sqlNFE = "INSERT INTO NFEArquivo(Id, Versao, NumeroNF, DataEmissao, CPF_CNPJ_Emitente, NomeEmitente, CPF_CNPJ_Destinatario, NomeDestinatario, TipoPessoaEmitente, TipoPessoaDestinatario, XMLNF) VALUES ('$Id', '$Versao','$nfNumeroNF', '$nfDataEmissao','$nfCPFCNPJEmit','$nfNomeEmit','$nfCPFCNPJDest','$nfNomeDest',1,1,'x')";
						echo $sqlNFE;
						$execNFE = mysql_query($sqlNFE, $conexao) or die("Não foi possível realizar a inserção");						
					}
				}
			}
	
?> 

Mas não estou conseguindo obter sucesso.

Se puderem me ajudar, agradeço.

 

Valeu e fiquem na paz

Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá, boa tarde.

Consegui resolver o problema, agora consegui "ler" o cabeçalho do XML.

Como estava tentando ler um "atributo" do mesmo a forma como tinha feito estava completamente equivocada.

Fiz a leitura por "array"

 

Fiz dessa forma e se alguém tiver a mesma dúvida:

 

 $Id = utf8_decode($xml->NFe[0]->infNFe->attributes()->Id); // para pegar o id
 $Versao = utf8_decode($xml->NFe[0]->infNFe->attributes()->versao); // para pegar a versão

Valeu e fiquem na paz.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Amigos, estava realizando testes de leitura nos cabeçalhos e descobri, dentre 19.000 arquivos xml de notas fiscais que não existe só um tipo. Um deles podemos ler como o amigo descreve aí em cima:

 

$arquivo1="DEMO/0001-nfe.xml";

$xml1 = simplexml_load_file($arquivo1);

$Id1 = utf8_decode($xml1->NFe[0]->infNFe->attributes()->Id); echo"$Id1 <HR>";

 

E o outro tem um nó a menos, o [NFe] no array. Como fazer pra uma consulta captar o erro de uma função ao tentar ler esse tipo com o nó a menos e passar a outra função para ler corretamente? Captando erro php e retornando?

 

Muito obrigado pela ajuda e abcs a todos coders aê ;]

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.