Question

I am trying to read text from files in a directory and have it be displayed as description text below an image. I have been able to use the STRIPOS function to separate out each part of the text, except am having trouble with the last section. The last section is titled "Description:" and actually runs into multiple lines. I don't know how to display more than just the line that reads "Description:". I want to print from "Description:" to the end of the file. I will post my code and the text file in this message.

$dirname = 'data';

$dirhandle = opendir($dirname);

$housestextarray = array();

if ($dirhandle)
        {
            while (false !==($file = readdir($dirhandle)))
            {
                if ($file !='.' && $file !='..')
                {
                    array_push($housestextarray, $file);
                }
            }

            closedir($dirhandle); 
        }

    sort($housestextarray);


    foreach ($housestextarray AS $housedescription)
        {
            $housetext = '';

            $description = '';

            $pos = stripos($housedescription, 'house_');

            if ($pos === false)
            {
                //nothing
            } else {
                    $lines_in_file = count(file($housedescription));

                    $fp=fopen($housedescription,"r");

                    for ($cntr = 1; $cntr <= $lines_in_file; $cntr++)
                {
                    $cityline=fgets($fp);
                    $priceline=fgets($fp);
                    $bedroomsline=fgets($fp);
                    $bathsline=fgets($fp);
                    $footageline=fgets($fp);
                    $realtorline=fgets($fp);
                    $grabberline=fgets($fp);

                    $descriptionline=fgets($fp);

                    //print $cityline;
                    //print $descriptionline;

                    //$housetext .= $line;

                    $citypos = stripos($cityline, 'City:');

                    if ($citypos === false)  //found the city line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $city= $cityline."<br />\n";
                        //print $city;
                    } 

                    $pricepos = stripos($priceline, 'Price:');

                    if ($pricepos === false)  //found the city line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $price = $priceline."<br />\n";
                        //print $price;
                    } 

                    $bedroomspos = stripos($bedroomsline, 'Bedrooms:');

                    if ($bedroomspos === false)  //found the city line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $bedrooms = $bedroomsline."<br />\n";
                        //print $bedrooms;
                    } 

                    $bathspos = stripos($bathsline, 'Baths:');

                    if ($bathspos === false)  //found the city line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $baths = $bathsline."<br />\n";
                        //print $baths;
                    } 

                    $footagepos = stripos($footageline, 'Footage:');

                    if ($footagepos === false)  //found the city line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $footage = $footageline."<br />\n";
                        //print $footage;
                    } 

                    $realtorpos = stripos($realtorline, 'Realtor:');

                    if ($realtorpos === false)  //found the realtor line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $realtor = $realtorline."<br />\n";
                        //print $realtor;
                    } 

                    $grabberpos = stripos($grabberline, 'Grabber:');

                    if ($grabberpos === false)  //found the grabber line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $grabber_formatted = str_replace('Grabber:','', $grabberline);
                        $grabber = "<h3>".$grabber_formatted."</h3><br />\n";
                        //print $grabber;
                    } 

                    $descriptionpos = stripos($descriptionline, 'Description: ');
                                                                    if ($descriptionpos === false)  //found the description line first time
                    {
                        //nothing
                    }
                    else
                    {
                        $description .= $descriptionline."<br />";

                        //print $description;

                    }
                }
                    $output = $grabber."<br/>".$city.$bedrooms.$baths;
                    $output .= $price.$footage.$realtor."<br />";
                    $output .= "<br />".$description."<br />";

                    print $output;

            }   

And here is the text file contents example (one of six files):

City: OceanCove
Price: $950,000
Bedrooms: 5
Baths: 3
Footage: 3000 sq. ft.
Realtor: Shirley Urkiddeng
Grabber: Fantastic Home with a Fantastic View!
Description:
You will never get tired of watching the sunset from your living room sofa or the sunrise from your back porch with a view overlooking the gorgeous coral canyon. Once in a lifetime opportunity!

UPDATED CODE WITH Branden's help:

    function houseDescriptions()
{
    //$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
    //$dirname = $DOCUMENT_ROOT.'data';
$dirname = 'data';

$dirhandle = opendir($dirname);

$housestextarray = array();

if ($dirhandle)
        {
            while (false !==($file = readdir($dirhandle)))
            {
                if ($file !='.' && $file !='..')
                {
                    array_push($housestextarray, $file);
                }
            }

            closedir($dirhandle); 
        }

    sort($housestextarray);


    foreach ($housestextarray AS $housedescription)
        {
                        $housetext = '';

                        $description = '';

                        $data ="";

                        $pos = stripos($housedescription, 'house_');

                        if ($pos === false)
                        {
                            //nothing
                        } else {
                            $file_handle = fopen($housedescription, "r");
                    $data = "";
                    while (!feof($file_handle)) {
                       $filestrings .= fgets($file_handle);
                    }
                    fclose($file_handle);

                    //You'll need to double check the Regex if it doesn't work.
                    $data = preg_split('#\b(City:|Bedrooms:|Baths:|Footage:|Realtor:|Grabber:|Description:)\b#', $filestrings);

                    $city = $data[0];
                    $bedrooms = $data[1];
                    $baths = $data[2];
                    $footage = $data[3];
                    $realtor = $data[4];
                    $grabber = $data[5];
                    $description = $data[6];                    
                    $output = $grabber."<br />".$city.$bedrooms.$baths;
                    $output .= $price.$footage.$realtor."<br />";
                    $output .= "<br />".$description."<br />";

                    print $output;

            }   

        }
        //return $output;
}
Was it helpful?

Solution

Updated with proper regex

fgets can have issues when trying to get a string out of text file, especially a long string, there may be a line break within it that you may not see in your text editing program. A better way to do this is to get all of the information from the text file and store it in a string, then handle all searches with preg_split(). This code below (assuming my regex is correct, you may need to recheck it) will get all of the variables from the text file for you.

//Append the file location to the file name
$housedescription = $dirname."/".$housedescription;

//Get all contents of the file and save them into $filestrings
$file_handle = fopen($housedescription, "r");
$data = "";
while (!feof($file_handle)) {
   $filestrings .= fgets($file_handle);
}
fclose($file_handle);

//Remove any pesky \n newlines that were added by the text file
$filestring = preg_replace("/[\n\r]/","",$filestrings); 

//Case Sensitive Regex Search, split the string into an array based on the keywords
$data = preg_split('/(City:|Price:|Bedrooms:|Baths:|Footage:|Realtor:|Grabber:|Description:)/', $filestring, -1, PREG_SPLIT_NO_EMPTY);

//Save all the keywords to vars
$city = "City: ".$data[0];
$bedrooms = "Bedrooms: ".$data[1];
$baths = "Baths: ".$data[2];
$footage = "Footage: ".$data[3];
$realtor = "Realtor: ".$data[4];
$grabber = "Grabber: ".$data[5];
$description = "Description: ".$data[6];

Notice the addition of $filestring = preg_replace("/[\n\r]/","",$filestrings); this will remove any extra new lines that were in the text file so there are no
's where you don't want them.

Of course the absolute ideal would be to store all of your data in a mysql database instead of .txt files, as it is more secure and much faster for data access. But if you prefer .txt try not to open the same file more than once.

Some notes to take from this: How to use Regular Expressions, fopen, fgets, preg_replace, preg_split

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top