将一个Linux Shell脚本命令转换为PHP

3

我面临的问题可能有一个简单的解决方案,但由于我不是php专家,所以找不到它。当我需要从php调用shell命令时,通常会这样做:

cmd = "convert file.pdf image.jpg";
shell_exec($cmd);

现在我有一个可以在shell上运行的命令,但我无法从php中运行它,所以我认为可能有一种方法能够用php语言表达相同的命令。

该命令:

for i in $(seq --format=%3.f 0 $nf); do echo doing OCR on page $i; tesseract '$imgdir/$imgdir-$i.ppm' '$imgdir-$i' -l eng; done

我的PHP尝试:

<?php
$imgdir = "1987_3";
$nf = count(new GlobIterator('filesup/'.$imgdir.'/*'));
$cmd = "for i in $(seq --format=%3.f 0 $nf); do echo doing OCR on page $i; tesseract '$imgdir/$imgdir-$i.ppm' '$imgdir-$i' -l eng; done"
shell_exec($cmd);
?>

我所得到的是:

PHP Notice:  Undefined variable: i in count.php on line 7

欢迎提出建议...谢谢

更新

我已经阅读了被标记为重复的问题,并且我理解的是我的“i”必须有一个引用,对于一个shell命令来说它有,但是当从php执行时它不起作用。

在这方面,我也尝试了以下未成功的方法:

<?php
$imgdir = "1987_3";
$nf = count(new GlobIterator('filesup/'.$imgdir.'/*'));
$cmd ="seq --format=%3.f 0 $nf";
$i = shell_exec($cmd);
$cmd = "tesseract 'filesup/$imgdir/$imgdir-$i.jpg' 'filesup/$imgdir/$imgdir-$i' -l eng; done";
shell_exec($cmd);
?>

1个回答

3

PHP会在双引号字符串中计算所有变量,例如:

<?php
    $i=5;
    echo "Your i is: $i";
?>

输出: 你的 i 值为:5

如果你想避免这种行为,可以使用单引号:

<?php
    $i=5;
    echo 'Your i is: $i';
?>

输出: 您的 i 是:$i

请按照以下方式更新您的代码:

<?php
    $imgdir = "1987_3";
    $nf = count(new GlobIterator('filesup/'.$imgdir.'/*'));
    $cmd = 'for i in $(seq --format=%3.f 0 $nf); do echo doing OCR on page $i; tesseract \'' . $imgdir/$imgdir . '-$i.ppm\' \'' . $imgdir . '-$i\' -l eng; done';    
    shell_exec($cmd);
?>

非常感谢,我不得不对代码进行一些小调整,但它确实有效,再次感谢! - Andrés Chandía

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接