3

Due to reasons that are have nothing to do with the actual question, I need to call and use an external script via PHP to perform a string replacement on a complete html document. The replacement strings and the source code need to be passded to this script via php exec(). For this example, I have used a simple python script to take over the replacement.

PHP script looks like this:

$source = file_get_contents("somehtmlfile.html");
$replaceString = "Some text in the HTML doc";
$replaceTo = "Some other text";
$parsedString = system("python replace.py $replaceString $replaceTo $source", $retval);
print ("Done:" .$mystring);

Then the Python script will do the following:

import sys
import string
dataFrom = sys.argv[1];
dataTo = sys.argv[2];
dataSourceCode = sys.argv[3];
rep = dataSourceCode.replace(dataFrom, dataTo);
print rep;

The problem is that I can't pass the complete html source as an argument to the shell, at least not in the way shown above. From what I understood, while the html code gets passed to the shell it interpretes some sections as commands (multiline could be an issue here I suppose).

The output I receive from the script :

sh: cannot open !DOCTYPE: No such file sh: cannot open html: No such file sh: cannot open head: No such file sh: cannot open title: No such file

... (this goes on)

Any suggestions?

8
  • I don't quite remember how quotes worked in php, but you probably have to do system('python replace.py "$replaceString" "$replaceTo" "$source"'), you wrap the arguments in double quotes.
    – BrtH
    Aug 16, 2012 at 10:31
  • Also note that you don't need the semicolon after each line in python.
    – BrtH
    Aug 16, 2012 at 10:34
  • Hi, I tried that but it doesent work :-/ (btw single quotes don't allow variable interpretation in PHP so this example would beed to be rewritten like this : system('python replace.py "'.$replaceString.'" "'.$replaceTo.'" "'.$source.'"'). Thanks
    – mspir
    Aug 16, 2012 at 10:35
  • Can't you just escape the quotes in php: system("python replace.py \"$replaceString\" \"$replaceTo\" \"$source\"")?
    – BrtH
    Aug 16, 2012 at 10:36
  • That would have the same effect. Not to forget, the html source is also full of doulble quotes (and single quotes sometimes) so this also creates a conflict.
    – mspir
    Aug 16, 2012 at 10:45

1 Answer 1

0

It is not working because there are spaces and quotes in the html text that you pass as an argument, so it is seen as multiple arguments. To solve this, you have to put quotes around the arguments.
The correct code is $parsedString = system("python replace.py '$replaceString' '$replaceTo' '$source'", $retval);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.