0

What is the best way to create a PHP array with HTML values in it? I need to be able to encode it to JSON and decode it successfully.

Ex: My PHP array looks like this:

Array
(
    [0] => Array
        (
            [Name] => <a href="http://gotourl.com?user=john+vz">john</a>
            [Sex] => M
        )

    [1] => Array
        (
            [Name] => <a href="http://gotourl.com?user=sue+hp">sue</a>
            [sex] => F
        )
)
Jake
  • 25,479
  • 31
  • 107
  • 168

3 Answers3

0

I don't know how you handle your data, or if you're using a JS Framework, but this is a small example, how it could work

$htmlAnchors = array (
    array (
            "Name" => '<a href="http://gotourl.com?user=john+vz">john</a>',
            "Sex" => "M"
        ),
    array(
            "Name" => '<a href="http://gotourl.com?user=sue+hp">sue</a>',
            "Sex" => "F"
        )
);

$jsonOutput = json_encode( $htmlAnchors );
?>
<!DOCTYPE html>
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>

        <div>TODO write content</div>
        <div id="anchors">
            <!--insert links here-->
        </div>
        <script type="text/javascript">
            var json = <?php echo $jsonOutput; ?>;
            json.forEach( function( entry ) {
                var anchors = document.getElementById( "anchors" );
                anchors.innerHTML = anchors.innerHTML + entry.Name + "</br>";
            });
        </script>
    </body>
</html>
swidmann
  • 2,787
  • 1
  • 18
  • 32
0

Just save the values, not the html structure.

$array   = array();
$array[] = array(
    "link"  => "http://gotourl.com?user=john+vz",
    "name"  => "john"
    , "sex" => "M"
);
$array[] = array(
    "link"  => "http://gotourl.com?user=sue+hp",
    "name"  => "sue"
    , "sex" => "F"
);
$string = json_encode($array);

transmit string and decode like:

$links = json_decode($string);
foreach ($links as $value) {
    printf('<a href="%s">%s Sex: %s</a>', $value['link'], $value['name'], $value['sex']);
}

You could think of any other structure to save the values. You don't need to save it using KVP, you could use nested arrays with named keys.

cb0
  • 8,415
  • 9
  • 52
  • 80
0

PHP's json_encode function does all the hard work for you. You can just create your array and encode it like this:

$people = array(
    array
    (
        'Name' => '<a href="http://gotourl.com?user=john+vz">john</a>',
        'Sex' => 'M'
    ),
    array(
        'Name' => '<a href="http://gotourl.com?user=sue+hp">sue</a>',
        'sex' => F
    )
);

$json = json_encode($people);
sg-
  • 2,196
  • 1
  • 15
  • 16