3

Im trying to echo some JSON Data. The problem is the data contains variables but my code isn't putting the variables into the string. Heres my code:

$status = $row['Status'];
$priority = $row['Priority'];
echo '{"status":"$status","priority":"$priority"}' ; 

this php is echoing

{"status":"$status","priority":"$priority"}

when I need to echo

{"status":"Completed","priority":"High"}

for example. How can I fix this?

1
  • 3
    You should not build json manually, use json_encode() instead. Commented Jul 4, 2016 at 11:13

4 Answers 4

6

Just use json_encode function

echo json_encode($row);
Sign up to request clarification or add additional context in comments.

Comments

5
json_encode($row) 

Will give you the desired output.

Comments

3

The problem here is that PHP does not substitute variables in single quotes, only in double quotes (see http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double).

For example:

$test = "a";
echo 'This is $test test and'.chr(10); 
echo "this is $test test.".chr(10); 

/*
   Creates the following output:
   This is $test test and
   this is a test.
*/

Note: chr(10) creates the new line.

And the solution to your problem is to use json_encode() and json_decode() as other people have suggested already. http://php.net/manual/en/function.json-encode.php

Comments

0

The problem is in your single quotes, PHP get all vars inside as strings, so break the string as follow:

echo '{"status":"'.$status.'","priority":"'.$priority.'"}' ;  

On top of that, you can use json_encode() in order not to build your JSON object manually.

Comments

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.