json_encode returning HTML tags

Asked

Viewed 469 times

-1

In performing echo json_encode($data);, I am receiving ,via console.debug(data), the following:

<br />
<font size='1'><table class='xdebug-error xe-notice' dir='ltr' border='1' cellspacing='0' cellpadding='1'>
<tr><th align='left' bgcolor='#f57900' colspan="5"><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> Notice: Undefined variable: v_prod_total in C:\wamp64\www\nfe\admin\nfephp-master\exemplos\NFe\4.00testaMakeNFe.php on line <i>464</i></th></tr>
<tr><th align='left' bgcolor='#e9b96e' colspan='5'>Call Stack</th></tr>
<tr><th align='center' bgcolor='#eeeeec'>#</th><th align='left' bgcolor='#eeeeec'>Time</th><th align='left' bgcolor='#eeeeec'>Memory</th><th align='left' bgcolor='#eeeeec'>Function</th><th align='left' bgcolor='#eeeeec'>Location</th></tr>
<tr><td bgcolor='#eeeeec' align='center'>1</td><td bgcolor='#eeeeec' align='center'>0.0020</td><td bgcolor='#eeeeec' align='right'>424896</td><td bgcolor='#eeeeec'>{main}(  )</td><td title='C:\wamp64\www\nfe\admin\nfephp-master\exemplos\NFe\4.00testaMakeNFe.php' bgcolor='#eeeeec'>...\4.00testaMakeNFe.php<b>:

What might be going on?

Script:

$http({
          method  : 'POST',
          url     : 'enviar.php',
          dataType: 'json',
          data : dados: dados ,
          headers : {'Content-Type': 'application/x-www-form-urlencoded'}
         })
         .success(function(data) {
            if (data.errors) {
              $scope.erroValidar = "Erro";
            } else {
              $scope.key = data.chave;
              console.debug(data);
            }
          })

Note: json_encode is among a "multitude" of PHP code

try{
        $query = $conecta->prepare('SELECT * FROM empresas WHERE situacao=1');
        $query->execute();
        $resultado = $query->fetchAll(PDO::FETCH_ASSOC);
    }catch (PDOexception $erro){
        echo 'Erro ao selecionar: '.$erro->getMessage();
    }

    foreach($resultado as $res){
        $razao_social_emt   = $res['cidade'];
        $nome_fantasia_emt  = $res['nome_fantasia'];
        $cnpj_emt           = $res['cnpj'];
        $insc_estadual_emt  = $res['insc_estadual'];
        $logradouro_emt     = $res['logradouro'];
        $numero_emt         = $res['numero'];
.
.
.
echo json_encode($data);
.
.
.
else {
    header('Content-type: text/html; charset=UTF-8');
    foreach ($nfe->erros as $err) {
        echo 'tag: &lt;'.$err['tag'].'&gt; ---- '.$err['desc'].'<br>';
    }
}
?>

  • json_encode is not returning a string containing the JSON representation of the values.

  • do tipo: {"a":1,"b":2,"c":3,"d":4,"e":5}

4 answers

2


Your code is returning an error message:

The variable v_prod_total is not defined.

In the file: C: wamp64 www nfe admin nfephp-master examples Nfe 4.00testaMakeNFe.php

Row: 464

Besides this, check if there are other variables not defined.

If they are numeric and are looped, place their values before the loop with the initial value equal to ZERO.

  • Just a moment @Allanandrade, I’ll check.

  • I can create a chat to explain some details?

  • You can. Quiet.

  • http://chat.stackexchange.com/rooms/51455/json-encode-retornando-tags-html

2

Let me translate what happened:

1 - This HTML with this class x-debug it’s not strange to me. You’re probably using the Xdebug extension in PHP.

2 - This HTML only appears when it is in error.

3 - There is a mistake. He is Notice: Undefined variable: v_prod_total. You are trying to access a variable that has not been defined.

4 - Problem is not function json_encode. If you solve the error, the return JSON will be correct (if there is no other error, of course).

  • x-debug is disabled: [xdebug]&#xA;zend_extension ="c:/wamp64/bin/php/php5.6.25/zend_ext/php_xdebug-2.4.1-5.6-vc11-x86_64.dll"&#xA;xdebug.remote_enable = off&#xA;xdebug.profiler_enable = off&#xA;xdebug.profiler_enable_trigger = off&#xA;xdebug.profiler_output_name = cachegrind.out.%t.%p&#xA;xdebug.profiler_output_dir ="c:/wamp64/tmp"&#xA;xdebug.show_local_vars=0

  • I already corrected the value of v_prod_total.

  • Following @nottherealhemingway’s advice, now the following error is displayed on the console: angular.min.js:117 SyntaxError: Unexpected token A in JSON at position 0 at JSON.parse (<anonymous>) at wc (angular.min.js:17) at dc (angular.min.js:91) at angular.min.js:92 at q (angular.min.js:7) at gd (angular.min.js:92)

1

I use the following headers to return JSON:

<?php

// No topo da página
header("Access-Control-Allow-Orgin: *"); // CORS
header("Access-Control-Allow-Methods: *"); // Verbos HTTP[S]: PATCH, PUT, DELETE, GET, POST
header("Content-Type: application/json");

Another thing is that your code is reading the condition passed in IF and returning what is in ELSE, which contains a header (header) that returns HTML. This HTML is simply formatting the error message generated by line 464 (4.00testaMakeNFe.php).

You can generate the error otherwise:

.
.
.
else {
    // Remove o cabeçalho
    foreach ($nfe->erros as $err) {
        errors[] = $err;
    }
    echo json_encode($err, JSON_NUMERIC_CHECK);
}
  • I made the modifications @nottherealhemingway, now the following error appears on the console: angular.min.js:117 SyntaxError: Unexpected token A in JSON at position 0&#xA; at JSON.parse (<anonymous>)&#xA; at wc (angular.min.js:17)&#xA; at dc (angular.min.js:91)&#xA; at angular.min.js:92&#xA; at q (angular.min.js:7)&#xA; at gd (angular.min.js:92)

  • Please do not use the code snippet to mark things like PHP or codes that are not executable within the site, the use of Trecho de código (Stack Snippet) is to run CSS, HTML and JS. PHP does not run inside the site. To put PHP use the Amostra de código (or by Shortcut Ctrl+K). Read to get this straight: http://meta.pt.stackoverflow.com/a/4463/3635

  • all right. It’s just that I was worried about solving a problem.

0

With the help of @Allanandrade, via chat, we were able to discover that the problem was in variáveis não inicializadas and in the chamada de outras funções/bibliotecas que estavam utilizando print_r, var_dump e echo.

Browser other questions tagged

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