2

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 {}
6
  • 3
    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. Commented Dec 11, 2013 at 21:36
  • 3
    Try utf8_encode($answer) before encoding to json. Commented Dec 11, 2013 at 21:38
  • That'll be useful only if the fetched data happens to be encoded in ISO-8859-1/latin1, though. Better to try and find out what exactly is going on first Commented Dec 11, 2013 at 21:39
  • I might be too tiered now but since when does the superglobal $_SESSION have class methods? Commented Dec 11, 2013 at 21:46
  • Adding utf8_encode($answer) does make it work! Thank you for the suggestion. Do you know what character exactly it was that makes it require such a encoding function? Line breaks? Semi Colons? Commented Dec 11, 2013 at 21:47

1 Answer 1

2

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

Unfortunately that does not help, the output is {"answer":{}}
then it must be the encoding problem you mention above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.