花了无数个小时试图弄清楚这一点无济于事。我得到了大量的XML文件,理想情况下是想找到将事务直接导入数据库的方法,所以我不必手动完成。
我已经设法达到以下结果,但无法弄清楚如何爆炸产品并使用相同的剩余细节将它们作为单独的交易分配给客户。
这是我到目前为止所尝试和管理的内容:
////Daily XML I get sent in this format
<trans>
<custtrans>
<cust>564</cust>
<cust_name>John David</cust_name>
<product>P1,P2,P3,P4</product>
<internal>Yes</internal>
</custtrans>
<custtrans>
<cust>877</cust>
<cust_name>James Harris</cust_name>
<product>P2</product>
<internal>No</internal>
</custtrans>
</trans>
////I'd Like the transactions to be recorded in mysql like this
cust |cust_name |product |internal
564 |John David |P1 |Yes
564 |John David |P2 |Yes
564 |John David |P3 |Yes
564 |John David |P4 |Yes
877 |James Harris |P2 |No
////This is how it is being inserted which I do NOT WANT
cust |cust_name |product |internal
564 |John David |P1,P2,P3,P4|Yes
877 |James Harris |P2 |No
////my PHP insert statement into database
$db = new PDO($dsn, $username, $password, $options);
$xml = simplexml_load_file('http://xml.com');
foreach ($xml as $insert)
{
try {
$stmt = $db->prepare('INSERT INTO customers (cust,cust_name,product,internal)
VALUES (:cust,:cust_name,:product,:internal)');
$stmt->execute(array(
':cust' => $insert ->cust,
':cust_name' => $insert ->cust_name,
':product' => $insert ->product,
':internal' => $insert ->internal,
));
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
答案 0 :(得分:1)
您可以将包含用逗号分隔的产品的字符串转换为产品数组,例如使用PHP中的explode()函数。
然后只需遍历阵列中的所有产品,插入每个产品。
示例:
foreach ($xml as $insert)
{
$productNamesSeparatedWithCommas = "P1,P2,P3,P4";
$productNamesArray = explode(",", $productNamesSeparatedWithCommas);
foreach ($productNamesArray as $singleProduct)
{
try {
$stmt = $db->prepare('INSERT INTO customers (cust,cust_name,product,internal)
VALUES (:cust,:cust_name,:product,:internal)');
$stmt->execute(array(
':cust' => $insert ->cust,
':cust_name' => $insert ->cust_name,
':product' => $singleProduct,
':internal' => $insert ->internal,
));
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}