json decode pada PHP gagal karena ada line break nya

Bismillahirrohmaanirrohiim….

Karena ini masalah klasik, dimana ketika kita punya string json yang besar biasanya ada masalah saat di decode jadi array.

Salah satu masalah utamanya adalah karena ada line break atau ganti baris, jika string json tersebut di decode dengan fungsi json_decode hasilnya akan error.

Nah cara sederhananya adalah dengan mereplace line break tersebut sebelum json di decode:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<?php
$json = preg_replace('/\r|\n/','\n',trim($json));
$array = json_decode($json, true);
<?php $json = preg_replace('/\r|\n/','\n',trim($json)); $array = json_decode($json, true);
<?php
$json = preg_replace('/\r|\n/','\n',trim($json));
$array = json_decode($json, true);

Sekian, semoga bermanfaat.

Bagikan
Baca Juga:   Mengirim POST menggunakan file_get_contents PHP

You May Also Like

About the Author: rasupe

Leave a Reply

Discover more from Rasupe

Subscribe now to keep reading and get access to the full archive.

Continue reading