0

I have results from a database that are returned as json encoded, I haven't got much experience in it so not too sure what's going here, however I have tried concatenating values to see if it works but it doesn't and it gets returned as is, i.e. markup.

while($row = $stmt->fetch()) {
    $return_arr[] =  '<a href="'.$row['slug'].'">'.$row['title'].'</a>';
    }

echo json_encode($return_arr);

which results in:

   <a href="link">title</a>

How can I return a hyperlink? I've also tried escaping the quotes.

Abu Nooh
  • 846
  • 4
  • 12
  • 42

2 Answers2

1

JSON is a data format with which you can transport data between endpoints (e.g. REST service - HTML client) or store data easily in nosql databases.

If you want your output to be clickable, drop the json_encode() and print your result directly.

while($row = $stmt->fetch()) {
    echo '<a href="'.$row['slug'].'">'.$row['title'].'</a>';
}
Community
  • 1
  • 1
QQping
  • 1,370
  • 1
  • 13
  • 26
  • Anyway to have it clickable in json? – Abu Nooh Mar 18 '15 at 22:27
  • JSON is not made to be an interactive format to display your data on the UI. If you want to make the hyperlink clickable, render the HTML. – QQping Mar 18 '15 at 22:29
  • Any suggestions on how to transport and then render it? – Abu Nooh Mar 18 '15 at 22:31
  • You can call your PHP which will output JSON with AJAX. jQuery has a pretty good AJAX handling. Also, you can read about Mustache to get a grip on how JSON can be used efficiently to render HTML. – QQping Mar 18 '15 at 22:33
0

Your second line of code has the / in </a> misplaced so the resulting HTML is corrupted.

Switch the second line of code to be

$return_arr[] =  '<a href="'.$row['slug'].'">'.$row['title'].'</a>';

EDIT

Let's also be clear about the code you've pasted in general. Assuming your $stmt->fetch() is returning valid data, the code above will create an HTML tag as an element in an array, and then echo the JSON encoded array. You won't get renderable HTML from that echo statement as is.

Adam Link
  • 2,783
  • 4
  • 30
  • 44
  • thanks for that, pdo statement is fine, and the type is here only. – Abu Nooh Mar 18 '15 at 22:26
  • To your comment below - JSON isn't clickable. It is a transfer format. It is not rendered in HTML. You'll have to drop the `json_encode()` – Adam Link Mar 18 '15 at 22:30