JSON created with PHP pass to JAVASCRIPT

Asked

Viewed 365 times

1

PHP reads a CSV file and generates a JSON

require __DIR__ . '\autoload.php';
use League\Csv\Reader;
$arq = __DIR__ . '\arquivos\201111019050.csv';

$reader = Reader::createFromPath($arq, 'r');
$records = $reader->getRecords();
$tmp = new SplTempFileObject();
foreach ($records as $offset => $record) {
    $tmp->fputcsv($record);
}

$reader = Reader::createFromFileObject($tmp);
$reader->setDelimiter(';');
$reader->setHeaderOffset(0);
$reader = json_encode($reader);
?>

Download JSON in PHP for JAVASCRIPT

<script>
    // ACHO QUE MEU ERRO ESTA AQUI 
    var arrayOfObjects = "<?="$reader"?>";
    // -----------------------------------
    for (var i = 0; i < arrayOfObjects.length; i++) {
        var object = arrayOfObjects[i];
        for (var property in object) {
            alert('item ' + i + ': ' + property + '=' + object[property]);
        }

    }
</script>

CVS File - 201111019050.csv

[
{"sistema":"xxxx","dt_ini":"01:16","dt_fim":"03:20","dt_esti":"03:13","job":"xxxxx"},
{"sistema":"aaaaa","dt_ini":"01:42","dt_fim":"03:46","dt_esti":"03:47","job":"aaaaa"},
{"sistema":"bbbbb","dt_ini":"01:17","dt_fim":"03:21","dt_esti":"03:25","job":"bbbbb"},
{"sistema":"ccccc","dt_ini":"02:28","dt_fim":"04:32","dt_esti":"04:42","job":"ccccc"},
]

1 answer

1

You have extra quotes and you should use ; in PHP. Then you have to parse that string for a JSON. You can do this in Javascript with JSON.parse

Mute:

var arrayOfObjects = "<?="$reader"?>";

for

var json = "<?=$reader;?>";
var arrayOfObjects = JSON.parse(json);
  • It hasn’t worked yet. <br> when I put the JSON data directly into the Javascript variable, it works, but when I take the php variable it doesn’t scroll.

  • @Leoneleloy can ask the question which HTML is produced on that line?

  • Sergio HTML this, as an answer !!!!!

Browser other questions tagged

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