Hello,

I'm stuck...been trying to come with asimple solution for hours. Here's my deal...

I have TXT file uploads going into my server from random users of my website...ALL uploaded TXT files are formatted the same way:

<file>polly_01.jpg</file> <cap>This is a test caption for image 1</cap>
<file>polly_02.jpg</file> <cap>This is a test caption for image 2</cap>
<file>polly_03.jpg</file> <cap>This is a test caption for image 3</cap>
<file>polly_04.jpg</file> <cap>This is a test caption for image 4</cap>
<file>polly_05.jpg</file> <cap>This is a test caption for image 5</cap>

Now, what I'd like to do is get some help with the code that will do the following:

  • Read the file

  • Parse the data from each line...in between the tags; example: polly_01.jpg, This is a test caption for image 1

  • Then put that data into my MySQL database, line by line.

If anyone can help I'd greatly appreciate the assistance!

Thanks in advance! All coding examples are VERY welcome!

    I'll assume you know how to insert it into the database yourself :p

    I usually use ereg_replace for this. Using file() to read each line in the file into an array, strip the new lines, then use ereg_replace to get two variables. One for the file, one for the caption.

    $file = file("txt.txt");
    foreach($file as $item) {
       $item = str_replace("\r","",$item); /* Damn Windows */
       $item = str_replace("\n","",$item); /* trim newlines */
    
       /* Get file */
       $f = ereg_replace(".*<file>","",$item);
       $f = ereg_replace("</file>.*","",$f);
    
       /* Get caption */
       $c = ereg_replace(".*<cap>","",$item);
       $c = ereg_replace("</cap>.*","",$c);
    }

      Beautiful code, and I think I'm on the right track here, BUT, something is wrong...

      With the above code, my first and ONLY $item in the foreach turns out to be this:

      <file>polly_01.jpg</file> <cap>This is a test caption for image 1</cap><file>polly_02.jpg</file> <cap>This is a test caption for image 2</cap><file>polly_03.jpg</file> <cap>This is a test caption for image 3</cap><file>polly_04.jpg</file> <cap>This is a test caption for image 4</cap><file>polly_05.jpg</file> <cap>This is a test caption for image 5</cap>

      Then the ONLY $f variable that comes out is:

      polly_31.jpg

      And, the ONLY $c variable that comes out is:

      This is a test caption for image 31

      Any ideas? Thanks in advance!

        In the text file, are they on seperate lines? file() reads each line into an array...

          Yes. Absolutely...and it seems that's where my problem is...the file() command isn't reading them into seperate array elements...

          Attaching my test TXT file...

            Opening it on Windows shows it as only one line

              Write a Reply...