How to turn content from a file into an array in PHP

Asked

Viewed 154 times

-1

I have a file that has a array with the translations of a website.

The contents of the file are similar to this:

var textHome = {
    "home": {
        "btn_contact": {
            "pt": "contato",
            "en": "contact",
        },
        "btn_home": {
            "pt": "Início",
            "en": "Home",
        },
        "bt_about": {
            "pt": "Sobre nós",
            "en": "About us",
        },
    }
};

I would like to read this file in php and turn it into an array, put it into a variable and pick up a specific language to add to the content of the site. Ta be necessary to use REGEX to remove "var textHome" and clean up something more unnecessary. You can help me?

  • 1

    Pq does not read as Javascript itself and picks up the object you want inside textHome?

  • I need to put in PHP because of Google searches.

  • not just write it right on the page by js script? <?php echo '<script></script>'?>

  • I have several places I need to put the texts. And I have to use a variable in PHP to get the content.

  • Split it by "=" that you have the object string. I believe that with this structure, you can use a json_decode(), test there

  • 1

    And why not manually switch this file to a standard that is supported in PHP? Dynamically analyzing this file will be a gigantic scam (or it will require a very well structured implementation, which probably won’t be the case). There are specific standards, including for translations. Why not use them?

Show 1 more comment

1 answer

4

First you need to get the contents of the file:

Suppose the file is called meu_js.js and is at the root of the application:

$file = file_get_contents('meu_js.js');

Remember to use your file in the method.

Done this you need to separate the declaration from the JSON variable:

$arr = explode('=',$file);

This will return you a vector with two positions:

array (size=2)
  0 => string 'var textHome ' (length=13)
  1 => string ' {
    "home": {
        "btn_contact": {
            "pt": "contato",
            "en": "contact",
        },
        "btn_home": {
            "pt": "Início",
            "en": "Home",
        },
        "bt_about": {
            "pt": "Sobre nós",
            "en": "About us",
        },
    }
};' (length=317)

The first position does not interest us, but the second one does. It is our JSON. We now need to turn it into a vector.

An important point to note is that this JSON of yours is invalid and will not be decoded by PHP. See why:

{
    "home": {
        "btn_contact": {
            "pt": "contato",
            "en": "contact",\\ <-- essa virgula torna o json inválido. O ultimo atributo do json não deve ter virgula
        },
        "btn_home": {
            "pt": "Início",
            "en": "Home",\\ <-- essa virgula torna o json inválido. O ultimo atributo do json não deve ter virgula
        },
        "bt_about": {
            "pt": "Sobre nós",
            "en": "About us",\\ <-- essa virgula torna o json inválido. O ultimo atributo do json não deve ter virgula
        },\\ <-- essa virgula torna o json inválido. O ultimo atributo do json não deve ter virgula
    }
};\\ <-- como extraímos o json separando a string pelo "=" esse ";" também torna o JSON inválido.

We need to clean JSON to get it read correctly. We have two options here, always ensure the correct writing of JSON or use regex. I will pass here the REGEX used to specifically clean the format you used. Depending on the JSON structure this REGEX may not work properly:

$json_str = str_replace(';','',$arr[1]);

Here we remove the ; from the end of the archive

$json_str = preg_replace('/(\},\s*\}\s*\})/','}}}',$json_str);

Here, we seek the occurrence of }, } }:

  • \} - the closing of the key;
  • , - followed by a comma;
  • \s* - followed by zero or more spaces;
  • \} - followed by another key lock;
  • \s* - followed by zero or more spaces;
  • \} - followed by another key lock;

And replaced by }}} thus removing the comma in

        },
    }
}

Finally, we will replace the commas within the attributes with a similar expression:

$json_str = preg_replace('/(\",\s*\})/','"}',$json_str);

Here, we’re looking for ", } and replacing by "}

  • \" - Literal double quotes;
  • \s - zero or more spaces;
  • \} - literal lock of keys;

Now, just decode the JSON and use it:

$json = json_decode($json_str);
var_dump($json);

object(stdClass)[5]
  public 'home' => 
    object(stdClass)[2]
      public 'btn_contact' => 
        object(stdClass)[1]
          public 'pt' => string 'contato' (length=7)
          public 'en' => string 'contact' (length=7)
      public 'btn_home' => 
        object(stdClass)[3]
          public 'pt' => string 'Início' (length=7)
          public 'en' => string 'Home' (length=4)
      public 'bt_about' => 
        object(stdClass)[4]
          public 'pt' => string 'Sobre nós' (length=10)
          public 'en' => string 'About us' (length=8)

Remembering that this will turn JSON into object. If you want array decode with:

$json = json_decode($json_str,true);

Some recommended readings:

Browser other questions tagged

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