我是php新手,想要一个可以识别外部文件中某些标签之间文本的脚本。
我设法找到答案here,它识别设置字符串中标签中的文本,但我不确定如何让文件识别外部文本文件中的标签。
PHP:
<?php
function innerh($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
$fullstring = "The <tag>Output</tag>"; // this is the string
$parsed = innerh($fullstring, "<tag>", "</tag>");
echo $parsed;
?>
外部文件:
<tag>This text</tag> <!-- This is the target -->
答案 0 :(得分:3)
与您已经在做的相似。目前,您正在使用该标记创建一个字符串,当您想要从文件中读取它时,您只需执行
$fullstring = file_get_contents('your-file.html');
无需其他更改。您可能需要提供该文件的完整路径,但这是关于它的。
该函数读取文件并以字符串形式返回其内容,您可以将其保存在变量中,就像手动构建变量一样。
答案 1 :(得分:0)
您的代码必须是这样的:
<?php
function innerh($string, $start, $end){
$string = " ".$string;
$ini = strpos($string,$start);
if ($ini == 0) return "";
$ini += strlen($start);
$len = strpos($string,$end,$ini) - $ini;
return substr($string,$ini,$len);
}
// Open a file with READ-ONLY flag ("r") and start of begining for read.
// See: http://php.net/manual/en/function.fopen.php
$fp = fopen("/path/to/file", "r");
// Check that file is opened and ready for read
if ($fp) {
// Until we have content on file, we resume reading
while (!feof($fp)) {
// Read from file, line by line.
// See: http://php.net/manual/en/function.fgets.php
$line = fgets($fp);
// Process line by line and print result
$parsed = innerh($line, "<tag>", "</tag>");
echo $parsed;
/* If your input file is a file without a new line or something like it,
just add a `$line = '';` before while line and change read line with
`$line .= fgets($fp);`, also remove process line and print line. After
that your file is on $line variable ;). */
}
}
?>