0

I have created php script which gets data and writes it to XML file. the task is executed by using for loop in php. for today execution it will run from 1 to 10. but when I will execute the script again I want it to continue from 11 to 20 in for loop. but as I have written for 1 to 10 in php file it will execute every time same. These values fetch the proper value from the server is their any way to update for value every time script execute. Sample Code:

    for ($i=1; $i<2; $i++)
{
    //$url = $link3;
    $url = $link1 . $i . $link2;
    // Set the url
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);

    $file=curl_exec($ch);


    $fileName = "data.xml";
if ( file_exists($fileName))    {
    $xml = simplexml_load_file($fileName);
}
else    {
    $xml= new SimpleXMLElement('<results />');
}
$array = json_decode ($file, true);
// Remove _class element
foreach ( $array['results'] as $key=>$result )   {
    unset($array['results'][$key]['_class']);
}
arrayToXml($array['results'], $xml);
$xml->asXML($fileName);

}

Based on the Value of i API URL is decided and I also refer page from API I can fetch max 10 page at a time. So i have to execute this script after few days .

7
  • 3
    Don't try to change the file, just try to think of a pointer to the last record done.. Maybe another sql table? Local file, anything for the script to read.. XY Problem ? Commented Apr 12, 2018 at 9:54
  • have you tried for ($i=$start; $i < $start + 10; $i++) {actions} ? Commented Apr 12, 2018 at 9:55
  • @AgniusVasiliauskas I agree, but given the question if the script is finished executing, the $start reference is lost. Commented Apr 12, 2018 at 9:57
  • it's not a big problem - he can save last val into database Commented Apr 12, 2018 at 9:58
  • If your adding to an XML file, can you show how this file is built? Commented Apr 12, 2018 at 9:58

1 Answer 1

2

You could try using sessions. Put this at the beginning of your code:

session_start();
if (!isset($_SESSION['start']) {
   $start = $_SESSION['start'] = 1;
}
else {
   $start = $_SESSION['start'] += 10;
}
session_write_close();

The first time you run the code $_SESSION['start'] will not be set and so $start will be 1. On subsequent runs $start will come from $_SESSION['start'] and will increment by 10 each time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.