0

Currently I have the following code, what I do is extract information from an XML, then I generate a CSV to be imported into my database manually. But I'm thinking about the possibility of avoiding generating the CSV file and better automatically insert what I extract into the database.

<?php
    require_once 'app/config.php';

    $xml = simplexml_load_file('xml/products.xml');

    $codes = [];
    foreach($xml->products as $i => $product) {
        $data = [];
        $data[] = (string)$product->key;
        $data[] = (string)$product->price;
        $data[] = (string)$product->quantity;
        $codes[] = $data;
    }

    $fp = fopen('products.csv', 'w');

    foreach ($codes as $code) {
        fputcsv($fp, $code);
        echo implode(',', $code) . '<br>';
    }

    fclose($fp);
?>

with the previous code, i get a file products.csv and the following:

A10001,18.50,85
A10002,19,12
...

i use MeekroDB to communicate with the database, so it could be something like this:

DB::insert('products', array(
  'key' => A10001,
  'price' => 18.50,
  'quantity' => 85
));

Can someone help me to insert all the information in the database to save me the process of exporting and importing the file? Thanks in advance for your time.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
David Noriega
  • 153
  • 1
  • 11
  • Looks right just try that DB::insert inside of foreach – Vinay Apr 14 '18 at 03:27
  • @Viney I understand, the problem is that I do not know how to obtain the data separately, I can do the insert but I can not separate for example the key $ product-> key; because I only get the first field. – David Noriega Apr 14 '18 at 03:34
  • @Viney 'key' => ???, 'price' => ???, 'quantity' => ??? – David Noriega Apr 14 '18 at 03:54
  • try `$data['key'] = (string)$product->key; ` (repeat for other variables) then you can just call `DB::insert('products', $code);` inside your `foreach` loop. – Nick Apr 14 '18 at 05:49

0 Answers0