This topic is locked

Import XML File

5/25/2011 3:03:00 PM
PHPRunner General questions
R
RockyMtnHi author

Without too much hoop jumping is it possible to import an xml file?

Thanks

P
procheck 5/25/2011

Hi,
What you need to do is create a php script to load the xml file and save your

fields to memory variables. Then you open your MySQL database in the same script and use the INSERT

command to update the table using the above variables.
Below is a working example to load the xml file and save it to variables. There

is some commented out code that was part of the original example which you can delete

if you don't want it.
// YOUR PHP SCRIPT

<?php

// set the XML file name as a PHP string

$myGroceryList = "groceries.xml" ;

// load the XML file

$xml = @simplexml_load_file($myGroceryList) or die ("no file loaded") ;

// assign the listName element to a string

// $nameOfMyShoppingList = $xml->listName ;

// echo "<h1>List: " . $nameOfMyShoppingList . "</h1>";
foreach ($xml->foodGroup as $foodGroup) {

// echo "<h2>Food group name is " . $foodGroup->groupName . "</h2>" ;

foreach ($foodGroup->item as $foodItem) {

echo "<br /> Item: " . $foodItem->name ;

echo "<br /> Quantity: " . $foodItem->howMuch ;

echo "<br />" ;

}

echo "<br />" ;

}
// add your MySQL INSERT code here
?>
// COPY THIS XML & SAVE THIS TO groceries.xml - SAME FOLDER

<?xml version="1.0"?>

<groceryList>

<listName>My Shopping List</listName>

<foodGroup>

<groupName>Fruits and Vegetables</groupName>

<item>

<name>Pomegranate</name>

<howMuch>2</howMuch>

</item>

<item>

<name>Carrots</name>

<howMuch>1 pound</howMuch>

</item>

</foodGroup>

<foodGroup>

<groupName>Grains</groupName>

<item>

<name>Couscous</name>

<howMuch>6 ounces</howMuch>

</item>

</foodGroup>

<foodGroup>

<groupName>Candy</groupName>

<item>

<name>Crunchie Bar</name>

<howMuch>1 gross</howMuch>

</item>

</foodGroup>

</groceryList>