0

I am struggling a bit to find the correct way of adding a php variable in my json string, with text added just in front of the variable. This is what I have got so far...

  $postData = '
  {
    "message": "Web order '.$order_number.'"
  }
  ';

When I look at the printout there is a line break just after "Web order", but otherwise nothing seems to go wrong... is this the way to do it?

3
  • Yes, decode the json first using json_decode then add whatever you want to add in the object/array(depending if you decoded it as an object or as an array) then re-encode it. Commented Oct 3, 2019 at 13:12
  • json_encode(array('message'=>"Web order ".$order_number)) Commented Oct 3, 2019 at 13:12
  • At a glance that looks like it should work. Are you confident that $order_number contains a value that can be cast to string? Commented Oct 3, 2019 at 13:12

2 Answers 2

1

If you want to use json string, then make sure you have properly use your values in your array.

Example:

<?
$order_number = 1;
$yourArray = array('message'=>"Web order ".$order_number);
echo json_encode($yourArray);
?>

Result:

{"message":"Web order 1"}

Here, i am using an array for your data $yourArray and then use json_encode() for json string.

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of concatenate string, use sprintf() Dealing directly with Json can become very harmful quickly. Prefer to use array then json_encode instead.

in your case, here is a simple example:

$message = sprintf('Web order %s', $order_number)
$postData = [
  'message' => $message
];

$json = json_encode($postData);

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.