如何逐行读取PHP输出并从每行创建HTML链接

时间:2017-01-18 14:28:23

标签: pdf php html

我有这个PHP脚本:

<?php

   $old_path = getcwd();
   chdir('/var/www/html/SEARCHTOOLS/');
   $term1 = $_POST['query1'];
   $term2 = $_POST['query2'];
   $var = "{$term1} {$term2}";
   $outcome = shell_exec("searcher $var");
   chdir($old_path);
   echo "<pre>$outcome</pre>";
?>

在搜索页面上写入两个搜索词并按下搜索按钮。搜索结果会显示为这样的网页:

/var/www/html/SEARCHTOOLS/1974-1991.pdf:1
/var/www/html/SEARCHTOOLS/1974-1991.pdf:3
/var/www/html/SEARCHTOOLS/1974-1991.pdf:7
/var/www/html/SEARCHTOOLS/1974-1991.pdf:7
/var/www/html/SEARCHTOOLS/1974-1991.pdf:9
/var/www/html/SEARCHTOOLS/1974-1991.pdf:13
/var/www/html/SEARCHTOOLS/1974-1991.pdf:13

结果显示该文件中单个PDF文件和页面编号的链接,但不可点击。

有没有办法让这些链接可以点击,以便在例如Evince或Acrobat中以正确的页码打开?

非常感谢提前。

/保

1 个答案:

答案 0 :(得分:0)

我找到了问题的正确答案。花了一些时间,但现在是:

<?php

// Get current working directory and put it as variable
   $old_path = getcwd();
// Change directory 
   chdir('/var/www/html/SEARCHTOOLS/');
// Create first variable as result of first searchword on searchpage
   $term1 = $_POST['query1'];
// Create second variable as result of second searchword on searchpage
   $term2 = $_POST['query2'];
// Create a variable combining first AND second variable
   $var = "{$term1} {$term2}";
// Create a variable as the result of the executed search using command "sokare" and variable "$var"
   $outcome = shell_exec("sokare $var");
// Return to starting directory
   chdir($old_path);
// Split the varible "$outcome" per line representing every page in PDF-file where variable "$var" is found
   foreach(preg_split("/((\r?\n)|(\r\n?))/", $outcome) as $line){
// Create a variable out of the given pagenumber in PDF-file
   $end = substr($line, strpos($line, ":") + 1);
// Trim the line by removing leading directories from line    
   $line2 = str_replace('/var/www/html', '', $line);
// Change a string from lower to upper case
   $line2 = str_replace('searchtools', 'SEARCHTOOLS', $line2);
// Remove the colon and anything behind it from line
   $line2 = array_shift(explode(':', $line2));
// Add suffix to line to facilitate linking to pagenumber in PDF-file
   $line3 = str_replace(" ", "_", $line2).'#page=';
// Add pagenumber from the variable "$end"
   $line3 = str_replace(" ", "_", $line3).$end;
// Print each line as a correct URL-link
   echo "<pre><a href=$line3>$line3</a></pre>";
}
?>

搜索结果现在会变为(并且可点击):

/SEARCHTOOLS/1974-1991.pdf#page=1
/SEARCHTOOLS/1974-1991.pdf#page=3
/SEARCHTOOLS/1974-1991.pdf#page=7

只是一个小编辑。这条线......

// Add suffix to line to facilitate linking to pagenumber in PDF-file
       $line3 = str_replace(" ", "_", $line2).'#page=';

...更适合:

// Add suffix to line to facilitate linking to pagenumber in PDF-file
   if (substr($line2, -3) == 'pdf') {
   $line3 = $line2.'#page=';

}