faqts : Computers : Programming : Languages : PHP : Sample Code

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

87 of 111 people (78%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How can I parse a text file delimited with a string of characters.

Jul 19th, 2004 23:35
Alder Rus, Philip Olson, Alok Sinha, Dhaval Desai, Onno Benschop, http://www.directoryonclick.com , http://www.singapore-yellow-pages.com


Here is a simple function to do what you need.  It both reads a file 
and
returns an array of deliminated strings.

This will work with both local files as well as files through HTTP (on
another server).  And for good measure, we'll create a global 
$splitfile
 array that contains information about errors.

<?php

function splitFile ($filename,$seperator)
{
global $splitfile;

  if (!isset($splitfile)) $splitfile = array();

  if (!is_readable($filename)) {
    $splitfile['errors'][] = "File ($filename) is not readable";
    return false;
  }

  $fp = fopen($filename, 'r');

  $contents = implode('', file($filename));

  if (!stristr($contents, $seperator)) {
    $splitfile['errors'][] = "Seperator ($seperator) not found
                              in file ($filename)";
    return false;
  }

  return explode($seperator, $contents);
}

?>

If this beast returns false, see what $splitfile has to say.  Otherwise
it will return an array of strings as per $seperator.