Search code examples
phpxmlsimplexml

PHP simplexml retrieve first n records in xml


i've just started using simplexml and i have the following statement that displays all the records in the xml:

$xml=simplexml_load_file("data.xml") or die("Error: Cannot create object");
foreach($xml->children() as $rec) { 
    echo $rec->dist . "<br />";
}

For pagination purposes, how would I go about retrieving a range of records from the xml, e.g. just the first 10 records (0-9)?

thx in advance!


Solution

  • You could try something like this :

    $children = $xml->children() ;
    $num = count($children) ;
    $start = 10 ; // zero-based index
    $end = 20 ; // zero-based index
    for ($i = $start; $i < $end ; $i++) {
        echo $children[$i]->dist . "<br />";
    }
    

    Previous version :

    $line = 1 ;
    foreach($xml->children() as $rec) { 
        echo $rec->dist . "<br />";
        if ($line++ == 10) break;
    }
    

    This will show 10 first elements.