sineverba
sineverba

Reputation: 5172

json_encode Array with int index

I need to encode a similar Array:

Array
(
    [0] => 393922111111
    [1] => 393433333333
    [2] => 393555555555
)

with json_encode.

I'm getting this:

["393922111111","393433333333","393555555555"]

that seems not correct. I.e. i put it into a

 echo '<input type="hidden" id="destinatariSMS" name="destinatariSMS" value="';
     echo json_encode($destinatariSMS);
 echo '" />'.PHP_EOL;

and in next page 'll receive only first bracket.

Could you gimme some hint? Thank you!

Upvotes: 2

Views: 548

Answers (2)

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

You do elementary mistake by not escaping your encoded json correctly prior putting is as INPUT value. Some characters, including " needs to be quoted (" => &quot;) to "work" with HTML. So valid code should be:

echo '<input type="hidden" id="destinatariSMS" name="destinatariSMS" value="';
echo htmlspecialchars(json_encode($destinatariSMS));
echo '" />'.PHP_EOL;

Upvotes: 2

jeroen
jeroen

Reputation: 91734

When you output to html, you should use htmlspecialchars to encode your output so that it cannot break the html:

 echo '<input type="hidden" id="destinatariSMS" name="destinatariSMS" value="';
     echo htmlspecialchars(json_encode($destinatariSMS));
 echo '" />'.PHP_EOL;

In your case the quotes in your json close the value attribute.

Upvotes: 0

Related Questions