Insert HTML into JSON Using PHP

Example:

I have this HTML Code

<select>
<option value=’1′>Bogor </option>
<option value=’2′>Jakarta</option>
<option value=’3′>Tanggerang</option>
</select>

Wanted:

I want to insert above code into JSON using PHP .. ?

Question:

How to do it … ?

Solution:

We can make like code below:

<?php
$data=”<select>”;
$data.=”<option value=’1′>Bogor </option>”;
$data.=”<option value=’2′>Jakarta</option>”;
$data.=”<option value=’3′>Tanggerang</option>”;
$data.=”</select>”;
json_encode(array(‘data’=>$data), JSON_UNESCAPED_SLASHES);

Explain:

  • All atribute inside HTML prefer quoted with single quote
  • JSON_UNESCAPED_SLASHES  mean do not escape /

Result:

The JSON data type is string and the result is:

“{“data”:”<select><option value=”1″>Bogor </option><option value=”2″>Jakarta</option><option value=”3″>Tanggerang</option></select>”}”

 

Thanks For Reading

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *