0

I have to work with a Ruby script that is dependent on a Gem. When the script is executed a JSON object is returned.

I am successfully executing the script using the following code.

<?php

$ruby = 'ruby ruby/teams.rb';

$res = system($ruby);

var_dump(json_decode($res, true));

The following is an example response from ruby/teams.rb

{"status"=>"active", "teamId"=>"XPLFKS59PK" }

My problem is that this printed directly to the screen and is not capture in the variable $res. When using var_dump(json_decode($res, true)) I get null.

What I would like to be able to do is capture the JSON response in the $res variable so I can convert to an array and worth with the data.

Any ideas if this is possible?

2
  • 2
    You should use exec instead of system. system returns only the last line of the executed command which in your case might be empty. Use exec and get all the output in an array. Commented Oct 4, 2017 at 14:00
  • Also realised I am not being returned a json array but a Ruby hash! Quick .to_json on the Ruby side sorted that. Commented Oct 4, 2017 at 14:23

2 Answers 2

1

My problem is that this printed directly to the screen and is not capture in the variable $res.

Most likely it sends its output to stderr instead stdout, so you need to redirect the streams yourself like this:

$ruby = 'ruby ruby/teams.rb 2>&1';

Here more about stream redirection: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html

Or, use exec() instead of system()

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

Comments

0

system only returns the last line of the commands output. In your case, i would use exec. Your code would look something like below

$ruby = 'ruby ruby/teams.rb';
exec($ruby, $res);
var_dump(json_decode(implode("", $res), true));

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.