Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

User Input to text to array

php user input array

  • Please log in to reply
1 reply to this topic

#1 Misanthrope

Misanthrope

    CC Lurker

  • Just Joined
  • Pip
  • 4 posts

Posted 21 October 2010 - 04:53 PM

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 ** 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?
  • 0

#2 Alexander

Alexander

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 21 October 2010 - 05:16 PM

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
  • 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.






Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download