tags:

views:

23

answers:

2

How to load the output buffer into a string using javascript ?

for example in php

<?php ob_start(); ?>

hello world !

<?php $string = ob_get_contents(); ?>
A: 

Hey Darseel, Try this

To be more specific, code is tested!

<?php ob_start(); ?>
hello world !
<?php $string = ob_get_contents(); ?>
<script type="text/javascript">
var MyJSStringVar = "<? echo trim($string)?>";
console.log(MyJSStringVar);
alert(MyJSStringVar);
</script>
JapanPro
A: 

If you are running PHP 5.2 or above, you can call json_encode() to automatically escape the string properly for JavaScript.

<?php ob_start(); ?>

hello world !

<?php $string = ob_get_contents(); ?>

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

For PHP 5.1 or below, you can use a compatibility library, like jsonwrapper, that adds the json_encode function for you.

Matthew Crumley