Asked  7 Months ago    Answers:  5   Viewed   31 times

I need to encode a javascript function into a JSON object in PHP.


$function = "function(){}";
$message = "Hello";

$json = array(   
      'message' => $message,
      'func' => $function
echo json_encode($json);



What I want is:


Can I do this with json_encode?



As Jani said, this is not possible directly with JSON, but this might help you:

Wednesday, March 31, 2021
answered 7 Months ago

It looks like it might be CakePHP.

See e()

e (mixed $data)

Convenience wrapper for echo().

This has been Deprecated and will be removed in 2.0 version. Use echo() instead.

See h()

h (string $text, string $charset = null)

Convenience wrapper for htmlspecialchars().

Wednesday, March 31, 2021
answered 7 Months ago

What's going on is that this is invalid JSON. The response from that url is incorrect--JSON doesn't allow the xXX two-digit hexadecimal binary escape sequences, only uXXXX unicode code point escape sequences. Here it should just be &, though--no escape sequence needed.

No idea why google/freebase is outputting invalid JSON.

Saturday, May 29, 2021
answered 5 Months ago

You need to read the file and decode it into an array, append to that array, and then write the whole array out.

$name =$_POST['n'];
$age = $_POST['a'];
$occ= $_POST['n'];
$country = $_POST['n'];

$old_contents = file_get_contents('somefile');
$jsoninfo = $old_contents ? json_decode($old_contents) : array();
$jsoninfo[] = array('name'=>$name,'age'=>$age,
$generated_json =  json_encode($jsoninfo);

echo $generated_json;

file_put_contents('somefile', $generated_json);
Saturday, May 29, 2021
answered 5 Months ago

I've done a very quick test :

$a = array(
    'id' => 152,
    'another' => 'test',
    'ananother' => 456,
$json = json_encode($a);
echo $json;

This seems to be like what you describe, if I'm not mistaken ?

And I'm getting as output :


So, in this case, the integers have not been converted to string.

Still, this might be dependant of the version of PHP we are using : there have been a couple of json_encode related bugs corrected, depending on the version of PHP...

This test has been made with PHP 5.2.6 ; I'm getting the same thing with PHP 5.2.9 and 5.3.0 ; I don't have another 5.2.x version to test with, though :-(

Which version of PHP are you using ? Or is your test-case more complex than the example you posted ?

Maybe one bug report on could be related ? For instance, Bug #40503 : json_encode integer conversion is inconsistent with PHP ?

Maybe Bug #38680 could interest you too, btw ?

Sunday, June 6, 2021
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :