Himmators
Himmators

Reputation: 15006

How to post an entire json object in php?

I have a json object that looks something like this:

Array ( 
[algorithm] => HMAC-SHA256 
[expires] => 1341331200 
[issued_at] => 1341326884 
[oauth_token] => AAADmtzfo7M4BAEjaqxcD5ofrPIlbAqn6WVV9Az63C5uRxZACrPnkvWddolF9cTW82g13ZAZCcc9z4RBFLZBAFwuflZB1NZAZBI2ZBFqLrm9KQQZDZD 
[user] => Array ( 
  [country] => se 
  [locale] => en_US 
  [age] => Array ( 
    [min] => 21 ) 
  ) 
  [user_id] => 651666483 
)

)

(printed using print_r) I want to add it to a javascript variable. by printing it to the html. What's the best way to do this?

Upvotes: 0

Views: 83

Answers (4)

niconoe
niconoe

Reputation: 1321

Maybe something like this:

<script type="text/javascript">
var myVar = <?php echo json_encode($myvar); ?>
</script>

Quick & Dirty...

Upvotes: 0

Samuel Parkinson
Samuel Parkinson

Reputation: 3112

Try this in your php page:

echo json_encode($your_array);

The json_encode function formats any array into a valid json formatted string.

See: http://php.net/json_encode

Upvotes: 2

Sirko
Sirko

Reputation: 74046

Just use json_encode() (PHP docu) to transform your object into a JSON object, which can directly be used as a object/array-literal in JavaScript.

// your array
$arr = array( ... );

// echo the JavaScript to set yourJsVar on a global scope
echo '<script> var yourJsVar = ' . json_encode( $arr ) . ';</script>';

Upvotes: 3

Mike Thomsen
Mike Thomsen

Reputation: 37506

Will json_encode work for you?

Upvotes: 0

Related Questions