I'm attempting to cherry pick elements from a large xml file (inventory for a boat dealer with all the specs for each unit) and push that data into two separate tables. I don't know if I need two Xpaths to do this or if it can be compressed into one.
The XML file holds about 50+ elements with child elements per boat but I wanted to take this one step at a time until I get the hang of doing this and left it at three, as an example, before adding complexities.
I used this previous answer to model the script so far and added what I needed:
<?php
$db = new mysqli('localhost', 'username', 'password', 'database');
$boats=simplexml_load_file("WinboatsWebXMLAllRevA.xml") or die ("Error: Cannot create object");
$values = <<<XPATH
(
|element
|element
|element
)
XPATH;
$pattern_custom = <<<SQL
INSERT INTO pmb_rsdirectory_entries_custom
(
column1, column2, column3
)
VALUES
(
'%s', '%s', '%s'
)
SQL;
foreach ($boats as $boat)
{
$data = $boat->xpath($values);
$escaped = array_map('mysql_real_escape_string', $data);
$query = vsprintf($pattern, $escaped);
$result - mysql_query($query);
if(mysql_errno())
{
printf(
'<h4 style="color: red;">Query Error:</h4>
<p>(%s) - %s</p>
<p>Query:
<pre>%s</pre>
</p>
</hr />',
mysql_errno(),
htmlspecialchars(mysql_errno()),
htmlspecialchars($query)
);
}
}
$values_custom = <<<XPATH
(
|element3
|element4
|element5
)
XPATH;
$pattern_custom = <<<SQL
INSERT INTO pmb_rsdirectory_entries
(
column3, column4, column5
)
VALUES
(
'%s', '%s', '%s'
)
SQL;
foreach ($boats as $boat)
{
$data = $boat->xpath($values_custom);
$escaped = array_map('mysql_real_escape_string', $data);
$query = vsprintf($pattern_custom, $escaped);
$result - mysql_query($query);
if(mysql_errno())
{
printf(
'<h4 style="color: red;">Query Error:</h4>
<p>(%s) - %s</p>
<p>Query:
<pre>%s</pre>
</p>
</hr />',
mysql_errno(),
htmlspecialchars(mysql_errno()),
htmlspecialchars($query)
);
}
}
?>
If there is a better way to manage this I am certainly open to suggestions.
Update (XML Snippet):
<document>
<node type="boat">
<uniqueid>ID00004146</uniqueid>
<category>Ski and Wakeboard Boat</category>
<boatyear>2015</boatyear>
<make>Malibu</make>
<model>Wakesetter 22 VLX</model>
<length units="feet">22.8</length>
<total>89630.00</total>
<engines>Single</engines>
<enginetype>Other</enginetype>
<fueltype>Gas</fueltype>
<hulltype>Fiberglass reinforced</hulltype>
<engine_manfacturer>Indmar</engine_manfacturer>
<eng_model>Monsoon 350HP 5.7L CAT</eng_model>
<eng_hp>350</eng_hp>
<newused>New</newused>
<availability>Out of Stock</availability>
<options>
<option>Ballast HI FLO - Bow Malibu Launch System</option>
<option>Ballast HI FLO - Rear PNP Plumbing</option>
<option>Pull Up Cleats - Two Pair</option>
<option>Wakesurf Technology (Same Color as Swim Platform)</option>
</options>
<pictures>
<picture>ID00004146_1.jpg</picture>
<picture>ID00004146_2.jpg</picture>
</pictures>
</node>
</document>