PHP json_decode() returns NULL with valid JSON?


I have this JSON object stored on a plain text file:

    "MySQL": {
        "Server": "(server)",
        "Username": "(user)",
        "Password": "(pwd)",
        "DatabaseName": "(dbname)"
    "Ftp": {
        "Server": "(server)",
        "Username": "(user)",
        "Password": "(pwd)",
        "RootFolder": "(rf)"
    "BasePath": "../../bin/",
    "NotesAppPath": "notas",
    "SearchAppPath": "buscar",
    "BaseUrl": "http:\/\/",
    "InitialExtensions": [
    "MediaPath": "media",
    "MediaGalleriesTable": "journal_media_galleries",
    "MediaTable": "journal_media",
    "Journal": {
        "AllowedAdFileFormats": [
        "AdColumnId": "3",
        "RSSLinkFormat": "%DOMAIN%\/notas\/%YEAR%-%MONTH%-%DAY%\/%TITLE%/",
        "FrontendLayout": "Flat",
        "AdPath": "ad",
        "SiteTitle": "Monte Maíz: Tu Sitio",
        "GlobalSiteDescription": "Periódico local de Monte Maíz.",
        "MoreInfoAt": "Más información aquí, en el Periódico local de Monte Maíz.",
        "TemplatePath": "templates",
        "WeatherSource": "accuweather:SAM|AR|AR005|MONTE MAIZ",
        "WeatherMeasureType": "1",
        "CurrencySource": "cotizacion-monedas:Dolar|Euro|Real",
        "TimesSingular": "vez",
        "TimesPlural": "veces"

When I try to decode it with json_decode(), it returns NULL. Why? The file is readable (I tried echoing file_get_contents() and it worked ok).

I've tested JSON against and it's perfectly valid.

What's wrong here?


Looking for answers on Google, I got back to SO: json_decode returns NULL after webservice call. My JSON file had the UTF BOM sequence (some binary chars that shouldn't be there), thus, breaking the JSON structure. Went to Hex Editor, erased the bytes. Everything's back to normal. Why has this happened? Because I edited the file using Microsoft Windows' Notepad. Terrible idea!

5/23/2017 12:02:43 PM

Accepted Answer

It could be the encoding of the special characters. You could ask json_last_error() to get definite information.

Update: The issue is solved, look at the "Solution" paragraph in the question.

3/9/2010 6:26:59 PM

This worked for me

json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow