here's my task. I've parsed an xml document and stored all of its data in an array. The array format is
Array(
[0]=> deals Object(
[deal_id]=>...
[deal_title]=>...
)
[1]=> deals Object(
[deal_id]=>....
[deal_title]=>...
)
)
what i need to do is to开发者_开发技巧 store values for each object in mysql database but not all of the object's tags should be stored in the same datatable. The reason why i first created the array is that the same php file will parse the xml and then will insert the values in the database OR if an entry with the same deal_id already exists in the database will update the appropriate tables. So I thought that having the xml in an array will help the further checking code. If anyone has a different suggestion I'd be glad to hear..
Thanks in advance!!!
<?xml version="1.0" encoding="UTF-8"?>
<deals>
<deal>
<id>1</id>
<title>title</title>
<city>city<city>
<price>20</price>
<url>http://....</url>
<previous_price>30</previous_price>
<discount> 10</discount>
<image>http://....</image>
<description> description</description>
<purchases> 1</purchases>
<address>address</address>
<latitude>30.5666</latitude>
<longitude>403.6669</longitude>
<start>datetime</start>
<end>datetime</end>
<active>true</active>
<category>category</category>
<type>type</type>
</deal>
</deals>
that's the xml file structure
This will do what you need:
foreach ($array as $deal) {
$title = mysql_real_escape_string($deal['deal_title']);
$id = int($deal['deal_id']);
if ($id) {
$query = "INSERT INTO deals (id, title) VALUES ($id, '$title') ON DUPLICATE KEY UPDATE deals SET title = '$title' WHERE id = $id";
mysql_query($query);
} else {
echo "ID is not a valid integer.";
}
}
Here is how to insert from the XML directly using PDO and Prepared Statements:
$deals = simplexml_load_string($xml);
foreach($deals->deal as $deal) {
// assuming you created a $pdo object before
$pdo->prepare(
'INSERT
INTO deals (id, title, …, type)
VALUES (:id, :title, …, :type)
ON DUPLICATE KEY
UPDATE deals
SET title = :title, …, type = :type
WHERE id = :id
');
$pdo->execute(
array(
':id' => (string) $deal->id,
':title' => (string) $deal->title,
…
':type' => (string) $deal->type,
)
);
}
Note that this will create one Query for each $deal in the XML. A more practical and performant approach is described in
- Bulk Insertion in MYSQL from XML Files
精彩评论