Joe Ainsworth
Joe Ainsworth

Reputation: 571

PHP to execute a Ruby script and capture the JSON result

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?

Upvotes: 0

Views: 93

Answers (2)

Panther
Panther

Reputation: 9408

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));

Upvotes: 0

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

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()

Upvotes: 1

Related Questions