I am trying to use an AJAX call to fetch some data and return multiple pieces of data to the caller through JSON. It works for certain tests that include simple output. But when one of the elements being returned is HTML, then it does not work. Any thoughts on this?
// get_answer() pulls some HTML back from an XML document
$answer = $_SESSION['quiz_session']->get_answer();
// test output to make sure everything is working
echo $answer;
/** sample output **
*
<div>
<p>
<b>
<span class="gloss-def">a downward slope</span>
</b>
</p>
<p>Because the village was situated on the
<i>declivity</i> of a hill, it never flooded.
</p>
<p>
<i>Synonyms: decline; descent; grade; slant; tilt</i>
</p>
</div>
*
** end sample output **/
echo json_encode($answer);
// will output {}
SunSparc
1,9222 gold badges23 silver badges48 bronze badges
1 Answer 1
Try adding $answer to and stdClass or an array, like
echo json_encode(array("answer"=>$answer));
Sign up to request clarification or add additional context in comments.
2 Comments
user1527739
Unfortunately that does not help, the output is {"answer":{}}
vrunoa
then it must be the encoding problem you mention above
lang-php
json_encode()will do that if it encounters non-UTF8 characters in the input. Your example doesn't seem to contain any such characters, though.utf8_encode($answer)before encoding to json.$_SESSIONhave class methods?