Skip to content

Instantly share code, notes, and snippets.

@thr3a
Created July 8, 2016 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thr3a/599d9529edb26979907e5489dcd140bd to your computer and use it in GitHub Desktop.
Save thr3a/599d9529edb26979907e5489dcd140bd to your computer and use it in GitHub Desktop.

PHPからJavascriptにデータを渡す方法としてJSON形式に変換がよく使われる。

<?php
$data = array(
  'name' => '太郎',
  'url' => 'https://github.com',
  'age' => 20,
  'is_human' => true
);
$json = json_encode($data);
?>

<script>
var json = JSON.parse('<?php echo $json; ?>');
console.log(json);
// => Object {name: "太郎", url: "https://github.com", age: 20, is_human: true}
</script>

しかし、このやり方だと配列に「"」や「'」が含まれるとエラーになる

<?php
$data = array(
  'name' => '太郎',
  'url' => 'https://github.com',
  'age' => 20,
  'is_human' => true,
  'symbol1' => "'",
  'symbol2' => '"'
);
$json = json_encode($data);
?>

<script>
var json = JSON.parse('<?php echo $json; ?>');
console.log(json);
// =>Uncaught SyntaxError: missing ) after argument list
</script>

解決策

原因は「"」や「'」がエスケープされていないため。PHPのjson_encodeではデフォルトだとエスケープしてくれない。

  • JSON_HEX_APOS
    • すべての ' を \u0027 に変換
  • JSON_HEX_QUOT
    • すべての " を \u0022 に変換

他にもある > http://php.net/manual/ja/json.constants.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment