1

I've been working on a personal project for a few days now, everything was working nicely, but since I've started on it again 2 hours ago I'm getting the following problem:

<html>
 <head>
  <title>Page Title</title>
 </head>
 <body>
  <?php
   $Testarray = array_map('str_getcsv', $content=file('Shows.csv'), array_fill(0,count($content), ";"));
   foreach($Testarray as $array)
    {
     foreach($array as $item)
     {
      print($item);
      print '<br/>';
     }
    }
  ?>
  <script type="text/javascript">
   var array = <?php echo json_encode($Testarray); ?>;
  </script>
 </body>
</html>

I'm allmost afraid to ask, but the 'var array' in Javascript is null. $Testarray is filled correctly, it prints the correct values. I've tried to do the same with a simple String and that works without a problem.

I've also tried var array = new Array(); prior to filling it. No effect.

Edit after trincot's reply:

var array = JSON.parse('<?php echo json_encode($Testarray); ?>'); 

Gives the following result in "Sources" in Chrome:

var array = JSON.parse(' ');

So it still doesn't seem to return anything.

Edit2: var_dump($testarray) (Sources in Chrome):

var_dump testarray

Final edit: The cause of the problem was a value in the xlsx file I exported from to a CSV file. The xlsx had a value with the ô character, which was replaced with in the CSV file. This caused for a nested null array in PHP and made everything go boom.

Using Eric's answer from another question, saving the xlsx file as xls and then saving the xls as CSV did the trick.

Community
  • 1
  • 1
Flats
  • 85
  • 1
  • 9
  • You should put quotes around `` to make it a string for Javascript, and then parse it as JSON – trincot Jan 07 '16 at 18:43
  • 1
    This is a possible duplicate of: - [How can I populate a javascript array with values from a database using PHP?](http://stackoverflow.com/questions/1416908/how-can-i-populate-a-javascript-array-with-values-from-a-database-using-php) – Stefano Saitta Jan 07 '16 at 18:43
  • json_encode() dumps out json only. It would **NOT** spit out a "json.parse()" call. that'd be entirely redundant. `var foo = JSON.parse(4);` and `var foo = 4` are essentially identical. – Marc B Jan 07 '16 at 19:26
  • I wonder, why nobody said, that you have a spaghetti code. It is not a good style to mix client and server code this way. Try to separate logic - divide and conquer. At least you should use some php template engine. – Jacobian Jan 07 '16 at 20:42
  • It might not be up to standard, but I can't automatically parse a CSV and then draw these locations via Google Maps API with just php or javascript. – Flats Jan 08 '16 at 08:46
  • I would not call this issue resolved at this moment. "Invalid Character" is not a correct resolution. `json_encode` is designed to correctly deal with most unicode characters, certainly `ô`. The problem is probably related to the use of non-UTF-8 encoded strings, and so this issue should not be considered closed yet. NB: issues are not solved by adding "[Solved..] to the title, but by accepting an answer. – trincot Jan 08 '16 at 13:49
  • Noted. Most likely it went wrong in the export from Excel to csv somewhere. It's not a problem that needs solving though, for now swapping the ô with an o (manually) fixed it. – Flats Jan 08 '16 at 15:42
  • I will go through your suggestions during the weekend. Thanks. – Flats Jan 08 '16 at 16:03

2 Answers2

2

The code is fine. JSON can be injected like that into Javascript, and it is abnormal that it just outputs a blank.

The var_dump output you added to the question confirms that there truly is an array in PHP which shows no apparent reason for this effect. I suggested to debug this, by outputting the JSON element by element:

    var array = [
    <?php
    foreach($Testarray as $array) {
        $output = json_encode($array); 
        echo "  $output,\n";
    }
    ?>
    ];

You reported that the first values were output correctly, but a problem occurred for a value with character ô. However, this is not the source of the problem. In a good configuration, the following code:

echo json_encode("ô");

will return: \u00f4

Which is the correct unicode number, and valid JSON, and will not lead to the effect you are having. Note that the last link also states:

The character encoding of JSON text is always Unicode. UTF-8 is the only encoding that makes sense on the wire, but UTF-16 and UTF-32 are also permitted.

The problem you are facing really is related to character encoding.

To solve this you should make sure the data is in UTF-8 encoding before passing it to json_encode. If you get it from a CSV file then make sure that file is saved as UTF-8.

The above would probably solve your issue, but it would be good also to follow the W3C instructions in Declaring character encodings in HTML, including (also) these:

  • Declare the UTF-8 encoding in your HTML, for example by adding <meta charset="UTF-8"> in the head section. Also start your file with <!DOCTYPE html>;

  • Make sure your PHP file is saved in UTF-8 character encoding. Most editors have an option for this, either under the Save As menu, or in some Preferences menu. If the editor offers the choice, include the Byte Order Mark. For example, notepad++ offers this possibility in the Encoding menu;

  • If you still face problems, verify PHP configuration settings concerning character encoding and HTTP output encoding. If you have non-default, non-UTF-8 values specified there, this may be the cause of your problems.

PHP.ini settings that influence encoding:

mbstring.internal_encoding    = UTF-8
mbstring.http_output          = UTF-8
trincot
  • 317,000
  • 35
  • 244
  • 286
  • This gives the following result in the Sources in Chrome: var array = JSON.parse(' '); – Flats Jan 07 '16 at 19:13
  • That means that you have a problem in PHP and the variable `$Testarray` really is empty (null or blank string, but not an array). Do you have errors reading the CSV file? `echo $content;` to check if there is anything read. – trincot Jan 07 '16 at 19:17
  • That's where the foreach echo's in the php script in the top is for. The array is correctly filled and printed on the page. – Flats Jan 07 '16 at 19:21
  • Just for testing (I know this is not what you need): could you only `json_encode` the first array element, and see if that works? `json_encode($Testarray[0])` ... adding the `[0]`. – trincot Jan 07 '16 at 20:00
  • That does return the right nested array! Is it just not possible to send multidimensional arrays from PHP to Javascript? – Flats Jan 07 '16 at 20:10
  • No, that should not be a problem. My hunch is that there might be a size problem. I put an alternative in my answer based on this finding. It would be interesting to see if something goes wrong halfway. – trincot Jan 07 '16 at 20:21
  • At last, redemption. The 97th entry had the letter ô in it, JSON couldn't handle it and it caused for a nested null array. You have my semi-eternal gratitude – Flats Jan 07 '16 at 20:37
  • One possible reason why json_encode failed on that, is that your PHP file is not saved in UTF-8 encoding. It would be worth checking if changing the file encoding (with save-as or options in your editor) resolves the problem. – trincot Jan 07 '16 at 20:43
  • 1
    Testing with `echo json_encode("ô");` I just get `"\u00f4"`. Therefore I think you have found a symptom of a deeper problem, but the fault seems not with `json_encode`. – trincot Jan 07 '16 at 20:56
0

Try doing JSON.parse("<?php echo json_encode($Testarray); ?>")

venkatKA
  • 2,399
  • 1
  • 18
  • 22