0

I need to access some variables from my site, elsewhere, via JSON.

All options will Always be defined. My question is, is it better to create a faux-json or use json_encode. The faux json would look something like this:

{
    "data": [
        {
            "optA": "<?php echo($optA); ?>",
            "optB": "<?php echo($optB); ?>",
            "optC": "<?php echo($optC); ?>"
        }
    ]
}

I 'feel' like nesting arrays and using json_ecode adds another step. Though, I know echo'ing out line by line adds some weight too.

I'd lean towards using json_encode because it's widely used. My arrays won't be overly complex either, but definitely more-so than the example above.

Xhynk
  • 13,513
  • 8
  • 32
  • 69
  • If you need to ask that question, you are unlikely to be on a scale where the difference in weight matters. If you think you are, measure first before making assumptions. – Evert Nov 01 '13 at 17:23
  • Thanks for the answers/comments guys. Good thing I asked before I started :P – Xhynk Nov 01 '13 at 17:28

2 Answers2

5

It is always better to use json_encode().

For starters, it does all the necessary escaping for you, so you can guarantee that your output is valid JSON.

In any case, if you want to format your code like that, indenting your array code, you can still do when you're writing it as a PHP array.

print json_encode(array(
    "data" => array(
            "optA" => $optA,
            "optB" => $optB,
            "optC" => $optC
    )
));

See, just as easy to read and to work with as your hard-coded JSON example, but doing it the right way.

Spudley
  • 166,037
  • 39
  • 233
  • 307
2

Use json_encode. It is less error prone. You won't break your code with unexpected data (such as strings containing new lines or quote marks) or typos.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335