How to read and interpret a JSON file with PHP?

Asked

Viewed 3,111 times

3

I am developing a PHP application, in which I am reading a JSON file (containing several electronic tax notes) and need to save some tags contained in this JSON file in variables.

I started studying PHP a little while ago, currently I am able to read the tags Discrimination of the JSON file and I made a very initial logic with some if’s using strpos.

I need to read the entire string of the Discrimination tag and check whether it contains the term "SUPPORT", "DEVELOPMENT" or "MAINTENANCE". And if it contains the specific term, save this result in a variable.

  • Is my logic correct? Is there anything that can be done to optimize something in my code?

Follow the JSON file:

{
"ConsultarNfseResposta": {
"ListaNfse": {
  "CompNfse": [
    {
      "Nfse": {
        "InfNfse": {
          "Numero": "12651",
          "CodigoVerificacao": "ECSV-FGRD",
          "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: MANUTENÇÃO",
            "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 - AFBR",
            "Endereco": {
              "Endereco": "ST 06",
              "Bairro": "Asa Sul",
              "CodigoMunicipio": "5300108",
              "Uf": "DF",
              "Cep": "15425845211"
            },
            "Contato": {
              "Email": "[email protected]"
            }
          },
          "OrgaoGerador": {
            "CodigoMunicipio": "2611606",
            "Uf": "PE"
          }      
        }
      }
    },

    {
      "Nfse": {
        "InfNfse": {
          "Numero": "12658",
          "CodigoVerificacao": "ECSV-NMBH",
          "DataEmissao": "2017-07-25T17:51:12",
          "NaturezaOperacao": "1",
          "OptanteSimplesNacional": "1",
          "IncentivadorCultural": "2",
          "Competencia": "2017-07-24T00:00:00",
          "Servico": {
            "Valores": {
              "ValorServicos": "9500",
              "IssRetido": "2",
              "BaseCalculo": "2350",
              "Aliquota": "0.02",
              "ValorLiquidoNfse": "2350"
            },
            "ItemListaServico": "0107",
            "CodigoTributacaoMunicipio": "6209100",
            "Discriminacao": "TAXA: DESENVOLVIMENTO",
            "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": "958451368500014"
              }
            },
            "RazaoSocial": "EXEMPLO - ATBR",
            "Endereco": {
              "Endereco": "ST 06",
              "Bairro": "Asa Sul",
              "CodigoMunicipio": "5300108",
              "Uf": "DF",
              "Cep": "15425845211"
            },
            "Contato": {
              "Email": "[email protected]"
            }
          },
          "OrgaoGerador": {
            "CodigoMunicipio": "2611606",
            "Uf": "PE"
          }
        }
      }
    },

    {
      "Nfse": {
        "InfNfse": {
          "Numero": "12659",
          "CodigoVerificacao": "ECSV-HFGS",
          "DataEmissao": "2017-07-25T17:51:12",
          "NaturezaOperacao": "1",
          "OptanteSimplesNacional": "1",
          "IncentivadorCultural": "2",
          "Competencia": "2017-07-25T00:00:00",
          "Servico": {
            "Valores": {
              "ValorServicos": "7600",
              "IssRetido": "2",
              "BaseCalculo": "7600",
              "Aliquota": "0.02",
              "ValorLiquidoNfse": "7600"
            },
            "ItemListaServico": "0107",
            "CodigoTributacaoMunicipio": "6209100",
            "Discriminacao": "TAXA: SUPORTE",
            "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": "95621548745210"
              }
            },
            "RazaoSocial": "EXEMPLO - NOBR",
            "Endereco": {
              "Endereco": "ST 06",
              "Bairro": "Asa Sul",
              "CodigoMunicipio": "5300108",
              "Uf": "DF",
              "Cep": "15425845211"
            },
            "Contato": {
              "Email": "[email protected]"
            }
          },
          "OrgaoGerador": {
            "CodigoMunicipio": "2611606",
            "Uf": "PE"
          }         
        }
       }
      }
     ]
    }
   }
  }

And also follow what I’ve done with PHP:

<?php

$json_data = json_decode(file_get_contents('arquivo.json'));

foreach ($json_data->ConsultarNfseResposta->ListaNfse->CompNfse as $data) {

    echo '<br>Número da nota: ' .$data->Nfse->InfNfse->Numero;
    echo '<br>Valor da nota: ' .$data->Nfse->InfNfse->Servico->Valores->ValorServicos;
    echo '<br>CNPJ do cliente: ' .$data->Nfse->InfNfse->TomadorServico->IdentificacaoTomador->CpfCnpj->Cnpj;
    echo '<br>Discriminação do serviço: ' .$data->Nfse->InfNfse->Servico->Discriminacao;
    echo '<br>';

    $stringSuporte = 'SUPORTE';
    $stringManutencao = 'MANUTENÇÃO';
    $stringDesenvolvimento = 'DESENVOLVIMENTO';


    $posSuporte = strpos($data->Nfse->InfNfse->Servico->Discriminacao, $stringSuporte);
    $posManutencao = strpos($data->Nfse->InfNfse->Servico->Discriminacao, $stringManutencao);
    $posDesenvolvimento = strpos($data->Nfse->InfNfse->Servico->Discriminacao, $stringDesenvolvimento);

    if ($posSuporte == true) {
        $servSuporte = $data->Nfse->InfNfse->Servico->Discriminacao;
        echo '<b>String encontrada: </b>' .$servSuporte;
        echo '<br>';
    } 

    if ($posManutencao == true) {
        $servManutencao = $data->Nfse->InfNfse->Servico->Discriminacao;
        echo '<b>String encontrada: </b>' .$servManutencao;
        echo '<br>';
    } 

    if ($posDesenvolvimento == true) {
        $servDesenvolvimento = $data->Nfse->InfNfse->Servico->Discriminacao;
        echo '<b>String encontrada: </b>' .$servDesenvolvimento;
        echo '<br>';
    }
}
?>

The output of my program is currently resulting in the following:

Número da nota: 12651
Valor da nota: 2350
CNPJ do cliente: 00085803000196
Discriminação do serviço: TAXA: MANUTENÇÃO
String encontrada: TAXA: MANUTENÇÃO

Número da nota: 12658
Valor da nota: 9500
CNPJ do cliente: 958451368500014
Discriminação do serviço: TAXA: DESENVOLVIMENTO
String encontrada: TAXA: DESENVOLVIMENTO

Número da nota: 12659
Valor da nota: 7600
CNPJ do cliente: 95621548745210
Discriminação do serviço: TAXA: SUPORTE
String encontrada: TAXA: SUPORTE
  • Discriminação do serviço always has TAXA: ... algo or that rate may vary?

1 answer

3


In place of strpos() can use strstr() to take the last part of the string and compare the loop value with array $tipos with the help of in_array().

$tipos = array('SUPORTE', 'MANUTENÇÃO', 'DESENVOLVIMENTO');

foreach ($json_data->ConsultarNfseResposta->ListaNfse->CompNfse as $data) {
    echo '<br>Número da nota: ' .$data->Nfse->InfNfse->Numero;
    echo '<br>Valor da nota: ' .$data->Nfse->InfNfse->Servico->Valores->ValorServicos;
    echo '<br>CNPJ do cliente: ' .$data->Nfse->InfNfse->TomadorServico->IdentificacaoTomador->CpfCnpj->Cnpj;
    echo '<br>Discriminação do serviço: ' .$data->Nfse->InfNfse->Servico->Discriminacao;
    echo '<br>';

    $tipoAtual = strstr($data->Nfse->InfNfse->Servico->Discriminacao, ' ');

    if(in_array($tipoAtual, $tipos)){
        printf('<b>String encontrada: </b> %s <br>', $data->Nfse->InfNfse->Servico->Discriminacao);
    }
}

Explanation:

Utilise strpost() without taking proper care is a tremendous hole, as it returns the position in which the passed string was found. This means that if it goes to zero your code generates a false positive. See this classic example:

$pos = strpos('X-salada', 'X');

if($pos == true){
    echo 'tem';
}else{
    echo 'não tem';
}

The exit is não tem. Usually (in languages with strong typing) does not compare booleans to true or false, simply omit the comparison pass the direct variable/expression, then use the operator == is not correct, in this case use the !== or === because he compares the value and the type.

$pos = strpos('X-salada', 'X');

if($pos !== false){
    echo 'tem';
}else{
    echo 'não tem';
}

The three ifs within the forech do the same thing printing something that changes is the one comparison || (OR) is already enough to eliminate them.

Code duplication:

if ($posSuporte == true) {
    $servSuporte = $data->Nfse->InfNfse->Servico->Discriminacao;
    echo '<b>String encontrada: </b>' .$servSuporte;
    echo '<br>';
} 

if ($posManutencao == true) {
    $servManutencao = $data->Nfse->InfNfse->Servico->Discriminacao;
    echo '<b>String encontrada: </b>' .$servManutencao;
    echo '<br>';
} 

if ($posDesenvolvimento == true) {
    $servDesenvolvimento = $data->Nfse->InfNfse->Servico->Discriminacao;
    echo '<b>String encontrada: </b>' .$servDesenvolvimento;
    echo '<br>';
}

It could turn into something as simple as:

if($data->Nfse->InfNfse->Servico->Discriminacao == 'TAXA: SUPORTE' ||
   $data->Nfse->InfNfse->Servico->Discriminacao == 'TAXA: MANUTENÇÃO' ||
   $data->Nfse->InfNfse->Servico->Discriminacao == 'TAXA: DESENVOLVIMENTO')
{
    echo '<b>String encontrada: </b>' . $data->Nfse->InfNfse->Servico->Discriminacao .'<br>';
}   

Related:

Identical sign "===" is only used in PHP? Why?

  • Very good your explanation rray. Recently I gave a modified in my code, but ended up keeping the strpos, after numerous tests, the application ta working as expected. Any problem, I can modify the logic and go the way you mentioned above. Thank you very much!!

Browser other questions tagged

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