-1

Basically I used these codes to transform:

echo "<script>";
echo " var img_array=new Array();";
foreach($img_arr as $img_url){
      $url=(string)$img_url;
      echo "img_array.push('".$url."');";
}

echo "console.log(img_array);";
echo "</script>";

However, errors occur(firefox debug window) :

Error: unterminated string literal
Source File: http://127.0.0.1/CubeCart/index.php?_a=account
Line: 1, Column: 42
Source Code:
    var img_array=new Array();img_array.push('http://gtms01.alicdn.com/tps/i1/T1mL3LFhhhXXaCwpjX.png 

but after I checked the souce file of the html page, the script is shown like this:

<script> var img_array=new Array();img_array.push('http://gtms01.alicdn.com/tps/i1/T1mL3LFhhhXXaCwpjX.png
      ');img_array.push('http://gtms01.alicdn.com/tps/i1/T1DQtTFsdFXXaCwpjX.png');console.log(img_array);</script>

With which I don't see anything is wrong.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Qing
  • 1,401
  • 2
  • 21
  • 41

2 Answers2

6
$jsArray = json_encode ($phpArray);
GordonM
  • 31,179
  • 15
  • 87
  • 129
  • 1
    in addition to this - recommended - answer, don't forget to use `JSON.parse(json_string)` in js to get an array back. – KarelG Feb 18 '14 at 07:37
  • @KarelG: You don't need to, valid JSON is valid JavaScript. – elclanrs Feb 18 '14 at 09:01
  • @elclanrs : uhm, i have said _in js_, because `json_encode` results into a string. By using `JSON.parse()`, you get an array for js, something the OP is asking for. – KarelG Feb 18 '14 at 09:41
  • 1
    OP is _printing_ JSON not _parsing_. This works just fine `var array = = json_encode(array(1,2,3)) ?>` – elclanrs Feb 18 '14 at 09:48
1

There is a newline in one of the items in your your php array. Use this:

echo "<script>";
echo " var img_array=new Array();";
foreach($img_arr as $img_url){
    $url=(string)$img_url;
    echo "img_array.push('". htmlentities(trim($url))."');";
}

echo "console.log(img_array);";
echo "</script>";
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
spassvogel
  • 3,479
  • 2
  • 18
  • 23