Greetings!

I am new to PHP and am having trouble getting the STRSTR() function to work.

I want to write a very simple "parser" that will output to a page only the lines in a file that match my variable $search.

<?php
// The search string...
$search = "VARCHAR";

// Get data file and file handle.
$fh = fopen("tableddl.db2", "r");

// Read the file into a string.
$string = fread($fh);

// We look for a match until we reach the end of the file.
while (!feof($fh)) {
    if(strstr($string, $search)) {
        $out = strstr($string, $search);
        echo $out;
    }
}
// Close data file.
fclose($fh);
?>

My data file is a DB2 script:

CREATE TABLE author (last_name VARCHAR(32) NOT NULL,
first_name VARCHAR(32) NOT NULL,
middle_initial VARCHAR(1),
author_id INTEGER GENERATED ALWAYS AS IDENTITY,
PRIMARY KEY (author_id));

My code works but stops at the first line ("CREATE TABLE..."). I want my code to output 3 lines like so (and ignore the lines that don't have the word "VARCHAR"):

CREATE TABLE author (last_name VARCHAR(32) NOT NULL,
first_name VARCHAR(32) NOT NULL,
middle_initial VARCHAR(1)

What am I doing wrong here? Can someone please help?

Thank you.

Al.

    fread() only reads one line from the file. You either need to use it in the while loop, or you could instead just use [man]file/man;

    $text = file("tableddl.db2");
    foreach($text as $string)
    {
       // now do your search/output stuff here
    }
    

      NogDog:

      I followed your suggestion and it works! This is my script

      <?php
      $search = "VARCHAR";
      
      $text = file("tableddl.db2");
      foreach($text as $string)
      {
             if(strstr($string, $search)) {
              $out = strstr($string, $search);
              echo $out;
          }
      }
      ?>

      A lot less code and a lot more effective!! 😃

      Thanks for your help!!

        Write a Reply...