【问题标题】:Pass multiline html as argument via php system()通过 php system() 传递多行 html 作为参数
【发布时间】:2012-08-12 16:04:45
【问题描述】:

由于与实际问题无关的原因,我需要通过 PHP 调用并使用外部脚本对完整的 html 文档执行字符串替换。替换字符串和源代码需要通过 php exec() 传递给这个脚本。对于这个例子,我使用了一个简单的 python 脚本来接管替换。

PHP 脚本如下所示:

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

那么 Python 脚本会执行以下操作:

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

问题是我不能将完整的 html 源代码作为参数传递给 shell,至少不能以上面显示的方式。据我了解,当 html 代码传递给 shell 时,它会将某些部分解释为命令(我想多行可能是一个问题)。

我从脚本收到的输出:

sh: 无法打开 !DOCTYPE: 没有这样的文件 sh: 无法打开 html: 没有这样的文件 sh: 无法打开 head: 没有这样的文件 sh:无法打开标题:没有这样的文件

...(继续)

有什么建议吗?

【问题讨论】:

  • 我不太记得引号在 php 中是如何工作的,但您可能必须这样做 system('python replace.py "$replaceString" "$replaceTo" "$source"'),将参数用双引号括起来。
  • 另请注意,python 中每行后不需要分号。
  • 嗨,我试过了,但它不起作用:-/(顺便说一句,单引号不允许 PHP 中的变量解释,所以这个例子应该像这样重写:system('python replace.py "'.$replaceString.'" "'.$replaceTo.'" "'.$source.'"')。谢谢
  • 你不能只转义php中的引号:system("python replace.py \"$replaceString\" \"$replaceTo\" \"$source\"")吗?
  • 会有同样的效果。不要忘记,html 源代码也充满了双引号(有时还有单引号),所以这也会产生冲突。

标签: php python shell exec


【解决方案1】:

它不起作用,因为您作为参数传递的 html 文本中有空格和引号,因此它被视为多个参数。要解决这个问题,您必须在参数周围加上引号。
正确的代码是$parsedString = system("python replace.py '$replaceString' '$replaceTo' '$source'", $retval);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    相关资源
    最近更新 更多