views:

48

answers:

2

Hi, Based on user's preferences I inject into my application a jason_encoded(translation array) which is later converted to javascript object and used by the application. Which, in your opinion, is the better way to do it?

Solution 1:

<head>
   <script type="text/javascript" src="lang.php"></script>
</head>

Solution 2 (code is executed inside index.php):

<head>
       <?php
           require_once(database_connect.php);
           //Prepare $myDictionary...

           $dictionary = json_encode($myDictionary);
           echo ("
              <script type='text/javascript'>
                 var dictionary=". $dictionary .";
              </script>
           ");

           require_once(database_close.php);
       ?>
</head>

I'am currently using the first solution, because I can cache the results, but I wan't to know if putting all that php code (including require/include functions) inside index.php is good or bad idea. Thanks for any suggestions.

+3  A: 

I would go with version one - it just looks tidier and separates stuff.

matpol
+3  A: 

Echoing HTML tags as strings (e.g. echo "<p>...</p>") is usually a bad way of using PHP. Use alternative syntax and avoid mixing too much of PHP and HTML. To be closer to MVC-approach it should look like this.

<?php

require_once(database_connect.php);
$dictionaryJSON = json_encode($myDictionary);
require_once(database_close.php);

// end of controller, begin of view
?>
<head>
    <script type='text/javascript'>
        var dictionary=<?php echo $dictionaryJSON ?>;
    </script>
</head>

And your first way looks also good, especially when you need to cache.

Denis Chmel