在PHP中创建一个函数

时间:2012-01-19 17:48:50

标签: php function

我经常使用它,并希望将其变成一个函数:

$f = fopen('../images/snotel/'. $name .'.pdf','w+');
fwrite($f, $pdf);
fclose($f);
$conv='/usr/bin/convert../images/snotel/'. $name .'.pdf ../images/snotel/'. $name .'.jpg'; 
system ($conv); 

这是我尝试的但它似乎不起作用:

function pdf2jpg($name)
{
    $f = fopen('../images/snotel/'. $name .'.pdf','w+');
    fwrite($f, $pdf);
    fclose($f);
    $conv='/usr/bin/convert../images/snotel/'. $name .'.pdf ../images/snotel/'. $name .'.jpg'; 
    system ($conv);
}

...

pdf2jpg('wsr');

1 个答案:

答案 0 :(得分:1)

实际上,您的函数会尝试在$pdf变量中写入没有数据的文件,因为您没有将其传入。

您需要做以下两件事之一:

此版本将PDF数据作为参数,并在函数中创建文件:

function pdf2jpg ($pdf, $name)     {
  $f = fopen('../images/snotel/'.$name.'.pdf','w');
  fwrite($f,$pdf);
  fclose($f);
  $conv = '/usr/bin/convert ../images/snotel/'.$name.'.pdf ../images/snotel/'.$name.'.jpg'; 
  //run 
  system($conv);
}

// Usage
pdf2jpg($pdf, 'wsr');

此版本只取名称,假设文件已存在:

function pdf2jpg ($name)     {
  $conv = '/usr/bin/convert ../images/snotel/'.$name.'.pdf ../images/snotel/'.$name.'.jpg'; 
  //run 
  system ($conv);
}

// Usage
$name = 'wsr';
$f = fopen('../images/snotel/'.$name.'.pdf','w');
fwrite($f,$pdf);
fclose($f);

pdf2jpg($name);