3

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??

2
  • 1
    Not sure why this user was downvoted. Commented Nov 7, 2014 at 11:37
  • The question was downvoted, not the user. @DickieBoy Commented Nov 7, 2014 at 12:13

1 Answer 1

3

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
)
Sign up to request clarification or add additional context in comments.

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.