Jump to content

User Input to text to array

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
Misanthrope

Misanthrope

    Newbie

  • Members
  • Pip
  • 4 posts
Hello people,
I make finally crossing-over to the PHP world in order to accomplish what I need to do.

I'm seeking to develop two scripts that will:

1) take user form input (a url) and write it to text (a list of urls)
2) take the urls in the text file and convert each into string to be stored in an array.

So far I think I've produced a semi-functional 1) but I'm having a hell of a time with 2).

Here's my code for the 1) script:


<?PHP


$filename = "url_list.txt";

$text = "\n" . $_POST['url1'];


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

if ($fp) {

fwrite ($fp, $text);

fclose ($fp);

}


else 

{

echo ("URL was not written!");

}


/* Re-direct to Index */

header("Location: index.php");

exit;

?>

Feel free to criticize it.

What I'm having trouble with is accomplishing number 2)

Anyone know how?

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,124 posts
You can always use the functions file_get_contents() and file_put_contents() as they were designed to simplify the task of reading/writing to a file. They are equivalent to using fopen() functions.

$filename = "url_list.txt";
$text = "\n" . $_POST['url1'];

//writing portion, we append $text to a file
if(!file_put_contents($filename, $text, FILE_APPEND)) {
    echo ("URL was not written!"); 
}

//reading portion, we store contents of $filename into $contents
$contents = file_get_contents($filename);
//explode each line into an array
$array = explode("\n", $contents);
echo $array[3]; //print line 4
You can read more about the functions here:
PHP: file_put_contents - Manual
PHP: file_get_contents - Manual
PHP: explode - Manual
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.