Extract XML information and insert into database with PHP

218 Views Asked by At

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.

0

There are 0 best solutions below