[Solved] How to edit my code to save to mySQL from the beginning of XML?


This should work for you:

<?php

    //Xml stuff
    $xml = simplexml_load_file("file.xml");

    //Database stuff
    $hostname = "localhost";
    $username = "root";
    $password = "";

    try {
        //DB Connection
        $dbh = new PDO("mysql:host=$hostname;dbname=dbname", $username, $password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        echo "Connected to Database<br/>";


        foreach($xml->products->product as $data) {
            $sql = "INSERT INTO XML_FEED (shop, product_id, product_name, product_link, product_image, product_category, product_price_with_vat)
                VALUES (:SHOP, :ID, :NAME, :LINK, :IMAGE, :CATEGORY, :PRICE)";
            $stmt = $dbh->prepare($sql);

            $params = array(
                "SHOP" => $xml->getName(),
                "ID" => $data->id ,
                "NAME" => $data->name,
                "LINK" => $data->link,
                "IMAGE" => $data->image,
                "CATEGORY" => $data->category,
                "PRICE" => $data->price_with_vat
            );
            $stmt->execute($params);

        }

        //Close Connection
        $dbh = null;

    } catch(PDOException $e) {
        echo $e->getMessage();
    }

?>

Site Note:

Add error reporting to the top of your file(s) which will help during production testing.

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
?>

Also if you want to show/see the data in html you can use this:

<?php

    //Xml stuff
    $xml = simplexml_load_file("file.xml");

    echo "<table border="1">";

    echo "<tr>
            <td>Shop</td>
            <td>Product ID</td>
            <td>Product Name</td>
            <td>Product Link</td>
            <td>Product Image</td>
            <td>Product Category</td>
            <td>Product Price with vat</td>
        </tr>";

    foreach($xml->products->product as $data) {
        echo "<tr>
            <td>" . $xml->getName() . "</td>
            <td>" . $data->id . "</td>
            <td>" . $data->name . "</td>
            <td>" . $data->link . "</td>
            <td>" . $data->image . "</td>
            <td>" . $data->category . "</td>
            <td>" . $data->price_with_vat. "</td>
        </tr>";
    }

    echo "</table>";

?>

1

solved How to edit my code to save to mySQL from the beginning of XML?