Grow your CSS skills. Land your dream job.

How to import only the first 10 XML items via HTTP…

  • # September 7, 2009 at 1:23 pm

    Does anybody know how to download only the first 10 XML items using PHP to download the XML file and then disconnect when the 10 items have been collected?

    I have a client that needs their site to access a XML feed that’s over 400mb! The host won’t allow the server to download a file that big, only file under 8mb. Just accessing the first few items would be ok so is there a way to open the download, collect 10 items and disconnect?

    Does that make sense?

    Cheers
    Matthew

    # September 14, 2009 at 5:32 pm

    Well you can do a loop to gather the first 10 items… that would be pretty easy. Something along the lines of:

    Code:
    $xml = simplexml_load_file(‘file.xml’);
    $i = 1;
    foreach($xml->tag as $data) {
    //do whatever with the $data inside that xml tag

    if ($i == 10)
    break;
    else
    $i++;
    }

    While that isn’t exactly the nicest/cleanest of code, it should work. It will do a loop 10 times, saving the string inside your tag to the $data variable. Just be sure to change the word ‘tag’ in the code to whatever you have in your xml files tag. If you have any questions just ask.

    -T

    # September 14, 2009 at 5:36 pm

    thanks for the help :)

    but simplexml_load_file caches the whole file in the server’s RAM, which is the problem

    # September 14, 2009 at 5:53 pm

    How are you retrieving the XML file? Are you using cURL? If so you might want to look at this option.

    CURLOPT_RANGE allows you to specify a range (in bytes) to transfer. For example 0-1023 would transfer the first 1kb of the file only. This would involve estimating how large the first 10 items of your XML is. If it turns out you need more of the file you could always make another request e.g. for the range 1024-2047 (the 2nd kb of the file).

    http://uk.php.net/manual/en/function.curl-setopt.php

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".