Reputation: 103
I want to call a php scripts from my ruby code. From ruby it needs to pass the arguments to php as command line arguments. But for argument with spaces it is treating it as command.
For example:
result = 'php sample.php "#{name}" "#{location}"'
It is returning
sh: line 1: Blahh Blahh: command not found
sh: line 2: Some more Blahh: command not found
Can anyone tell how to pass ruby string as argument??
Upvotes: 3
Views: 1568
Reputation: 102036
You can use the backticks syntax to make system calls.
But the issue is really that you need to pass the -f
option to PHP to tell PHP to execute a file instead of trying to run the command line arguments.
test.rb:
path = File.dirname(__FILE__) + '/'
args = ['arg1', 'arg2']
puts `php -f #{ path + 'sample.php'} { args.join(' ') }`
sample.php
<?php
if (isset($argv)){
print_r($argv);
}
Output:
Array
(
[0] => ./sample.php
[1] => arg1
[2] => arg2
)
Edit
You can also use the StdLib component Shellwords to escape and quote the arguments for you:
require 'shellwords'
path = File.dirname(__FILE__) + '/'
args = ['arg1', 'arg2 asdas']
puts `php -e #{ path + 'test.php'} #{ Shellwords.join(args) }`
Output
Array
(
[0] => ./test.php
[1] => arg1
[2] => arg2 asdas
)
Upvotes: 3