0

Trying to create a new php file from a template file using the PHP script below. There are no errors but the script is not working.

<?php

//loop through stock.json
$stock = json_decode("../stock.json");
$stockValue = $stock["stock"];

try {
    for($i = 0; $i < sizeof($stockValue); $i++) {
        $stock_id = $stockValue[i][0];
        //read template
        $template = file_get_contents("../../product_pages/product_page-0000.php");
        //create new file
        if (!file_exists("../../product_pages/product-".$stock_id.".php")) {
            $handle = fopen("../../product_pages/product_page-".$stock_id.".php", "c+");
            fwrite($handle,$template); 
            fclose($handle); 
        }
    }
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}
?>

The script is supposed to open "product_page-0000" and then save a copy of it with the new filename "product_page-$stock_id". $stock_id is obtained from the json file "stock.json".

The script is currently not outputting anything and there are no error codes.

  • negation in !file_exists is ok? Also you check file exist on product-000 not product_page-000 – daremachine Nov 02 '19 at 21:55
  • This answer says that "file_exists" with negation is okay though?https://stackoverflow.com/questions/4253487/check-if-file-exists-in-php – George Spyrou Nov 02 '19 at 22:02
  • it say if file product-000 does not exist then create new product_page file. I dont know if is ok. Only first look at your code. – daremachine Nov 02 '19 at 22:04
  • Changed that and still not working unfortunately. Also, there is no stock value "0000". "0000" is assigned to the template only – George Spyrou Nov 02 '19 at 22:07
  • `$stockValue[i][0];` should probably be `$stockValue[$i][0];` – M. Eriksson Nov 02 '19 at 22:10
  • Also, `son_decode("../stock.json");` should probably be `son_decode("../stock.json", true);` since you want that function to return an array, not an object. Make sure that you have `error_reporting()` set to `E_ALL` and that display errors is turned on while you develop. The above code should throw some warnings about the above mentioned issues. – M. Eriksson Nov 02 '19 at 22:11
  • I felt any misstype @MagnusEriksson :), if your code without $ not throw any error you should probably enable this for better understand whats going on – daremachine Nov 02 '19 at 22:12
  • Thanks, still hasn't fixed it unfortunately – George Spyrou Nov 02 '19 at 22:14
  • Well, we don't know what any of your variables contains, what your file system looks like and have already pointed out several issues. If you have fixed all those issues and turned on error reporting and display errors, the next action would be to do some more debugging to see exactly what action that fails. – M. Eriksson Nov 02 '19 at 22:18
  • Issue now solved. The contents of the of the stock.json were never set to a variable after decoding – George Spyrou Nov 02 '19 at 22:47

0 Answers0