Search code examples
phpfopenfgets

PHP return value of $title variable from a flat file


I am working on a script that returns the literal value of the $title variable that is at the top of a php file. At the end of the script, I use rtrim() to get rid of the quote and semicolon at the end of the string however, they will not trim. The top of my php file looks like this:

<php
$title="Test Title";
$description="Test Description";
?>

When I echo the string, I get:

Test Title;"

Here is my code. Can anyone tell me what I am doing wrong? I'd even welcome any suggestions for improving this:

<?php
//returns the value of the $title variable from the top of a php file.
$file = fopen("test.php", "r") or die("Unable to open file!");
$count = 0;
while ($count < 10) {                   //only check the first 10 lines
    $line = fgets($file);
    $isTitle = strpos($line, "itle=");         //check if $title is part of the string
    if ($isTitle !== false) {
        $fullTitle = explode("=\"", $line);      //explode it into two on =" which also trims the first quote
        $untrimmedTitle = $fullTitle[1];         //save the second part of the array as a string since rtrim needs a string
        $title = rtrim($untrimmedTitle, "\";");    //trim the quote and semi-colon from the string 
        $count = 10;                               //push the count up to 10 so it ends the loop
    }
    $count++;
}
echo $title;                                //show the title
fclose($file);
?>

Solution

  • Change $title = rtrim($untrimmedTitle, "\";"); to $title = rtrim(trim($untrimmedTitle), "\";");. It will be fine.

    At the end of $untrimmedTitle there is a break like \n.