0

I need to send this form of data :

 $objectData = '{"userid":"abc", "action":"def","data":"data"}';  

I have the vars already :

$userID=htmlspecialchars($_GET["userid"]);
$action=htmlspecialchars($_GET["action"]);
$data=htmlspecialchars($_GET["data"]);

How should i create $objectData with these fields inside(userid/action/data)?

Something similar i know (OBJ-C) [stringWithFormat:" %@, %d", "a", 5 ];

3
  • Why complicate things, can't you use normal PHP string concatenation? Commented Oct 22, 2015 at 11:12
  • or you can build an array, and jsonencode it. Commented Oct 22, 2015 at 11:13
  • FYI, the use of htmlspecialchars is unnecessary/misplaced/abused/wrong here. Commented Oct 22, 2015 at 11:16

4 Answers 4

3

So you want to create a json string. You can use stdClass(); to create an empty object and use json_encode() to make it a json string.

$objectData = new stdClass();
$objectData->userid = $userID;
$objectData->action = $action;
$objectData->data = $data;
$objectData = json_encode($objectData);
Sign up to request clarification or add additional context in comments.

Comments

3

That is JSON, produce it with json_encode.

echo json_encode([
    'userid' => $_GET['userid'],
    'action' => $_GET['action'],
    'data'   => $_GET['data']
]);

Or simply:

echo json_encode($_GET);

Since, apparently $_GET already has the array structure you want.

Comments

1

Form array and then using json_encode() you can generate json string

<?php

$userID=htmlspecialchars($_GET["userid"]);
$action=htmlspecialchars($_GET["action"]);
$data=htmlspecialchars($_GET["data"]);
$jsonArray = array('userid' => $userID, 'action' => $action, 'data' => $data);

echo json_encode($jsonArray);

// TO DECODE JSON STRING

echo json_decode($jsonbject);

?>

Comments

0

In Php you can simply concatenate strings with a dot. Like this:

$objectData = '{"userid":"' . $userID . '", "action":"' . $action . '","data":"' . $data . '"}';  

2 Comments

While yes, you can do that, it's probably a bad idea to do so, because you're risking producing invalid JSON.
No denying in that, but this works also when you don't produce JSON.

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.