1
I’m developing a program in which I need to read and interpret a JSON file, which is actually an XML file transformed into JSON. I need to select and take some information from this JSON file and save it in variables such as note number, its value, client cnpj etc.
Below is the JSON file (I edited some values).
{
"ConsultarNfseResposta":{
"ListaNfse":{
"CompNfse":[
{
"Nfse":{
"InfNfse":{
"Numero":"12651",
"CodigoVerificacao":"ECSV-EJZZ",
"DataEmissao":"2017-07-25T17:51:12",
"NaturezaOperacao":"1",
"OptanteSimplesNacional":"1",
"IncentivadorCultural":"2",
"Competencia":"2017-07-25T00:00:00",
"Servico":{
"Valores":{
"ValorServicos":"2350",
"IssRetido":"2",
"BaseCalculo":"2350",
"Aliquota":"0.02",
"ValorLiquidoNfse":"2350"
},
"ItemListaServico":"0107",
"CodigoTributacaoMunicipio":"6209100",
"Discriminacao":"TAXA: SERVIÇO DE VOTAÇÃO ELETRÔNICA",
"CodigoMunicipio":"2611606"
},
"PrestadorServico":{
"IdentificacaoPrestador":{
"Cnpj":"41069964000173",
"InscricaoMunicipal":"2427745"
},
"RazaoSocial":"INFORMATICA LTDA",
"Endereco":{
"Endereco":"RUA 241",
"Numero":"241",
"Bairro":"Exemplo",
"CodigoMunicipio":"2611606",
"Uf":"PE",
"Cep":"52030190"
},
"Contato":{
"Telefone":"33254854",
"Email":"[email protected]"
}
},
"TomadorServico":{
"IdentificacaoTomador":{
"CpfCnpj":{
"Cnpj":"00085803000196"
}
},
"RazaoSocial":"EXEMPLO - AMBR",
"Endereco":{
"Endereco":"ST 06",
"Bairro":"Asa Sul",
"CodigoMunicipio":"5300108",
"Uf":"DF",
"Cep":"15425845211"
},
"Contato":{
"Email":"[email protected]"
}
},
"OrgaoGerador":{
"CodigoMunicipio":"2611606",
"Uf":"PE"
}
}
}
}
]
}
}
}
In the script PHP I am managing to decode the JSON file and play it for a variable, as well as display the information on the screen with the print_r
organized, but I’ve tried everything and I can’t get a foreach to work, so I can get certain values in this file.
Follow my php code:
<?php
$json = file_get_contents('arquivo.json');
$json_data = json_decode($json,true);
echo '<pre>' . print_r($json_data, true) . '</pre>';
//logica do foreach
?>
I only put one item, in fact, it’s almost 50.
Post JSON as well, since this XML has been converted.
– William Aparecido Brandino
That’s an XML and not json.
– rray
With the foreach you will go through certain arrays. From what I understand of your problem, you have to enter the keys of your decoded JSON and get to the array you want to list. For example: echo '<pre>' . print_r($json_data['Consultarnfseresposta']['Listanfse']['Compnfse'][0]['Nfse'], true) . '</pre>';
– Walmir Silva
@RORSCHACH may even be dup of some question that already exists on the site, but I believe it is not the one that posted, it seems that using json_decode he already knows, what he does not know is to work with arrays and/ or objects (
->
).– Guilherme Nascimento