0

I have an API that takes parameters from a post through JSON and I want to extract one of the values in an array for a key value pair. However, despite many attempts, I can't get it to work.

Here is my code:

$json = file_get_contents('php://input'); 
$request = json_decode($json, true);
$parameters = $request["result"]["parameters"];

When I log $parameters to a text file, it log as

 {"numberofhits":"5"}

However, my efforts to capture the value 5 are not working:

$numhits = $json['numberofhits']; logs as empty.

So does:

$numhits = $parameters->numberofhits;

How can I capture the value 5 in a variable?

8
  • What do you get when you var_dump() the $parameters variable? Commented May 11, 2017 at 18:14
  • 1
    according to your code $json is just a string from a file. No way $json['numberofhits'] will work Commented May 11, 2017 at 18:15
  • 1
    @adjan He might have made a typo asking the question. The $parameters->numberofhits should have worked just fine. Something doesn't add up. Commented May 11, 2017 at 18:17
  • Not sure how to var_dump in this case. To see output I have to log to text file as input is coming from a third party. Commented May 11, 2017 at 18:18
  • if your data is being posted, i think php will take ur json and serialize it to the $_POST array global variable. $numHits = $_POST['result']['parameters'] Commented May 11, 2017 at 18:19

2 Answers 2

1

From your code above $json is a string and not a json object, your should use $request to access numberofhits

$request['numberofhits']
Sign up to request clarification or add additional context in comments.

Comments

0

If your $parameters just shows {"numberofhits":"5"}, this means your post request just returned a json of a json. Try json decoding $parameters again like json_decode($parameters, true); and log that result. It should log the desired array.

2 Comments

When I log that it is empty.
Are you sure your $parameters just shows {"numberofhits":"5"}? Coz if it does, the above should work just fine.

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.