php - 将 XML 导入 MySQL,无法获取所有子标签

标签 php mysql xml arrays csv

首先让我从我们在这里所做的事情开始: 我们从一台服务器中提取一个 XML 文件并将其放入另一台服务器中,这也是 php 代码所在的位置。 然后需要将一些 XML 数据导入到本地 MySQL 数据库中。 XML 是在线商店订单的副本。有些订单包含该人订购的多件商品,有些订单则不包含该人仅订购的一件商​​品。

对于 XML 示例,我们有:

<?xml version="1.0" encoding="UTF-8"?>
<xmldata>
  <Orders>
    <OrderID>2119</OrderID>
    <AddressValidated>Y</AddressValidated>
    <Affiliate_Commissionable_Value>2.0000</Affiliate_Commissionable_Value>
    <AuthHash>d995fd9424fb99e80f58841a0ff2340f</AuthHash>
    <AVS />
    <BillingAddress1>122 27th West</BillingAddress1>
    <BillingAddress2>Floor 11</BillingAddress2>
    <BillingCity>New York</BillingCity>
    <BillingCompanyName />
    <BillingCountry>United States</BillingCountry>
    <BillingFaxNumber />
    <BillingFirstName>Dan</BillingFirstName>
    <BillingLastName>Test</BillingLastName>
    <BillingPhoneNumber>646456777</BillingPhoneNumber>
    <BillingPostalCode>10001</BillingPostalCode>
    <BillingState>NY</BillingState>
    <CardHoldersName />
    <CC_Last4 />
    <CreditCardAuthorizationDate>3/30/2012 11:52:00 AM</CreditCardAuthorizationDate>
    <CreditCardAuthorizationNumber>MANUAL</CreditCardAuthorizationNumber>
    <CreditCardTransactionID />
    <Customer_IPAddress>184.56.49.45</Customer_IPAddress>
    <CustomerID>19</CustomerID>
    <CVV2_Response />
    <GiftWrapNote />
    <IsAGift>N</IsAGift>
    <LastModBy>7</LastModBy>
    <LastModified>3/30/2012 1:39:00 PM</LastModified>
    <Locked>Y</Locked>
    <Order_Comments>Test sale - Don't process
Ignore statuses on this order</Order_Comments>
    <Order_Entry_System>PHONE</Order_Entry_System>
    <OrderDate>3/30/2012 11:01:00 AM</OrderDate>
    <OrderNotes />
    <OrderStatus>Ready to Ship</OrderStatus>
    <PaymentAmount>8.1600</PaymentAmount>
    <PaymentMethodID>17</PaymentMethodID>
    <PONum />
    <Processed_AutoEvents>Y</Processed_AutoEvents>
    <SalesRep_CustomerID>7</SalesRep_CustomerID>
    <SalesTax1>0.1700</SalesTax1>
    <SalesTax2>0.0000</SalesTax2>
    <SalesTax3>0.0000</SalesTax3>
    <SalesTaxRate>0</SalesTaxRate>
    <SalesTaxRate1>0.08375</SalesTaxRate1>
    <SalesTaxRate2>0</SalesTaxRate2>
    <SalesTaxRate3>0</SalesTaxRate3>
    <ShipAddress1>123 27th West</ShipAddress1>
    <ShipAddress2>Floor 1</ShipAddress2>
    <ShipCity>New York</ShipCity>
    <ShipCompanyName />
    <ShipCountry>United States</ShipCountry>
    <ShipFaxNumber />
    <ShipFirstName>Dan</ShipFirstName>
    <ShipLastName>Test</ShipLastName>
    <ShipPhoneNumber>646782342</ShipPhoneNumber>
    <Shipping_Locked>Y</Shipping_Locked>
    <ShippingMethodID>1</ShippingMethodID>
    <ShipPostalCode>10001</ShipPostalCode>
    <ShipResidential>Y</ShipResidential>
    <ShipState>NY</ShipState>
    <Stock_Priority>3</Stock_Priority>
    <Tax1_IgnoreNoTaxRules />
    <Tax1_Title>Tax (8.375%)</Tax1_Title>
    <Tax2_IgnoreNoTaxRules />
    <Tax2_IncludePrevious>0</Tax2_IncludePrevious>
    <Tax2_Title />
    <Tax3_IgnoreNoTaxRules />
    <Tax3_IncludePrevious>0</Tax3_IncludePrevious>
    <Tax3_Title />
    <Total_Payment_Authorized>0.0000</Total_Payment_Authorized>
    <Total_Payment_Received>7.0700</Total_Payment_Received>
    <TotalShippingCost>5.9900</TotalShippingCost>
    <VendorID>0</VendorID>
    <OrderDetails>
      <OrderDetailID>3374</OrderDetailID>
      <AutoDropShip>Y</AutoDropShip>
      <FreeShippingItem>Y</FreeShippingItem>
      <GiftTrakNumber>0</GiftTrakNumber>
      <GiftWrap />
      <GiftWrapCost>0.0000</GiftWrapCost>
      <GiftWrapNote />
      <IsKitID />
      <KitID />
      <Locked>Y</Locked>
      <OnOrder_Qty>0</OnOrder_Qty>
      <OptionIDs />
      <Options />
      <OrderID>2119</OrderID>
      <ProductCode>test-product</ProductCode>
      <ProductID>39200</ProductID>
      <ProductName>Test Product 1</ProductName>
      <ProductNote />
      <ProductPrice>1.0000</ProductPrice>
      <ProductWeight>1</ProductWeight>
      <QtyOnBackOrder>0</QtyOnBackOrder>
      <QtyOnHold>1</QtyOnHold>
      <QtyShipped>0</QtyShipped>
      <Quantity>1</Quantity>
      <TaxableProduct>Y</TaxableProduct>
      <TotalPrice>1.0000</TotalPrice>
      <Vendor_Price>0.0000</Vendor_Price>
      <Warehouses />
    </OrderDetails>
    <OrderDetails>
      <OrderDetailID>3386</OrderDetailID>
      <AutoDropShip />
      <FreeShippingItem>Y</FreeShippingItem>
      <GiftTrakNumber>0</GiftTrakNumber>
      <GiftWrap />
      <GiftWrapCost>0.0000</GiftWrapCost>
      <GiftWrapNote />
      <Locked>Y</Locked>
      <OnOrder_Qty>0</OnOrder_Qty>
      <Options />
      <OrderID>2119</OrderID>
      <ProductCode>test-product</ProductCode>
      <ProductID>39200</ProductID>
      <ProductName>Test Product 2</ProductName>
      <ProductNote />
      <ProductPrice>1.0000</ProductPrice>
      <ProductWeight>1</ProductWeight>
      <QtyOnBackOrder>0</QtyOnBackOrder>
      <QtyOnHold>1</QtyOnHold>
      <QtyShipped>0</QtyShipped>
      <Quantity>1</Quantity>
      <TaxableProduct>Y</TaxableProduct>
      <TotalPrice>1.0000</TotalPrice>
    </OrderDetails>
  </Orders>
  <Orders>
    <OrderID>2141</OrderID>
    <AddressValidated>Y</AddressValidated>
    <Affiliate_Commissionable_Value>1.0000</Affiliate_Commissionable_Value>
    <AuthHash>14cca8be8db44ca9943f0a6cbf592c83</AuthHash>
    <AVS />
    <BillingAddress1>122 27th West2</BillingAddress1>
    <BillingAddress2 />
    <BillingCity>New York2</BillingCity>
    <BillingCompanyName />
    <BillingCountry>United States</BillingCountry>
    <BillingFaxNumber />
    <BillingFirstName>Dan2</BillingFirstName>
    <BillingLastName>Test2</BillingLastName>
    <BillingPhoneNumber>646346322</BillingPhoneNumber>
    <BillingPostalCode>10002</BillingPostalCode>
    <BillingState>NY</BillingState>
    <CardHoldersName />
    <CC_Last4 />
    <CreditCardAuthorizationDate>3/30/2012 3:33:00 PM</CreditCardAuthorizationDate>
    <CreditCardAuthorizationNumber>MANUAL</CreditCardAuthorizationNumber>
    <CreditCardTransactionID />
    <Customer_IPAddress>56.75.23.34</Customer_IPAddress>
    <CustomerID>19</CustomerID>
    <CVV2_Response />
    <GiftWrapNote />
    <IsAGift>N</IsAGift>
    <LastModBy>7</LastModBy>
    <LastModified>3/30/2012 3:33:00 PM</LastModified>
    <Locked>Y</Locked>
    <Order_Comments>Test sale #2, don't process, ignore status.</Order_Comments>
    <Order_Entry_System>PHONE</Order_Entry_System>
    <OrderDate>3/30/2012 3:32:00 PM</OrderDate>
    <OrderNotes />
    <OrderStatus>Ready to Ship</OrderStatus>
    <PaymentAmount>7.0700</PaymentAmount>
    <PaymentMethodID>17</PaymentMethodID>
    <PONum />
    <Processed_AutoEvents>Y</Processed_AutoEvents>
    <SalesRep_CustomerID>7</SalesRep_CustomerID>
    <SalesTax1>0.0800</SalesTax1>
    <SalesTax2>0.0000</SalesTax2>
    <SalesTax3>0.0000</SalesTax3>
    <SalesTaxRate>0</SalesTaxRate>
    <SalesTaxRate1>0.08375</SalesTaxRate1>
    <SalesTaxRate2>0</SalesTaxRate2>
    <SalesTaxRate3>0</SalesTaxRate3>
    <ShipAddress1>123 27th West2</ShipAddress1>
    <ShipAddress2 />
    <ShipCity>New York2</ShipCity>
    <ShipCompanyName />
    <ShipCountry>United States</ShipCountry>
    <ShipFaxNumber />
    <ShipFirstName>Dan2</ShipFirstName>
    <ShipLastName>Test2</ShipLastName>
    <ShipPhoneNumber>6461234789</ShipPhoneNumber>
    <Shipping_Locked>Y</Shipping_Locked>
    <ShippingMethodID>1</ShippingMethodID>
    <ShipPostalCode>10002</ShipPostalCode>
    <ShipResidential>Y</ShipResidential>
    <ShipState>NY</ShipState>
    <Stock_Priority>3</Stock_Priority>
    <Tax1_IgnoreNoTaxRules />
    <Tax1_Title>Tax (8.375%)</Tax1_Title>
    <Tax2_IgnoreNoTaxRules />
    <Tax2_IncludePrevious>0</Tax2_IncludePrevious>
    <Tax2_Title />
    <Tax3_IgnoreNoTaxRules />
    <Tax3_IncludePrevious>0</Tax3_IncludePrevious>
    <Tax3_Title />
    <Total_Payment_Authorized>0.0000</Total_Payment_Authorized>
    <Total_Payment_Received>7.0700</Total_Payment_Received>
    <TotalShippingCost>5.9900</TotalShippingCost>
    <VendorID>0</VendorID>
    <OrderDetails>
      <OrderDetailID>3404</OrderDetailID>
      <AutoDropShip>Y</AutoDropShip>
      <FreeShippingItem>Y</FreeShippingItem>
      <GiftTrakNumber>0</GiftTrakNumber>
      <GiftWrap />
      <GiftWrapCost>0.0000</GiftWrapCost>
      <GiftWrapNote />
      <IsKitID />
      <KitID />
      <Locked>Y</Locked>
      <OnOrder_Qty>0</OnOrder_Qty>
      <OptionIDs />
      <Options />
      <OrderID>2141</OrderID>
      <ProductCode>test-product</ProductCode>
      <ProductID>39200</ProductID>
      <ProductName>Test Product</ProductName>
      <ProductNote />
      <ProductPrice>1.0000</ProductPrice>
      <ProductWeight>1</ProductWeight>
      <QtyOnBackOrder>0</QtyOnBackOrder>
      <QtyOnHold>1</QtyOnHold>
      <QtyShipped>0</QtyShipped>
      <Quantity>1</Quantity>
      <TaxableProduct>Y</TaxableProduct>
      <TotalPrice>1.0000</TotalPrice>
      <Vendor_Price>0.0000</Vendor_Price>
      <Warehouses />
    </OrderDetails>
  </Orders>
</xmldata>

如您所见,第一个订单包含两个 <OrderDetails>,而第二个订单仅包含一个。

到目前为止,我已经创建了四个函数,这让我非常接近。

processxml();
processxmldetails();
vl_readytoship_download();
csvimport();

第一个从其他服务器导入 .xml 文件,以便我们可以开始工作。

function vl_readytoship_download() {
echo "Downloading Ready To Ship Orders...<br>";
$ch = curl_init("http://www.link.to/vl_rts.xml");
$fh = fopen("vl_rts.xml", "w");
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);
curl_close($ch);
}

第二个函数将 XML 转换为 CSV,以便我们可以更好地读取它以进行导入(这一步可能不是必需的,也可能是最好的方法,这就是我在这里的原因,但是,它确实有效。)

function processxml() {
vl_readytoship_download();
echo "Processing Ready To Ship Orders...<br>";
$filexml='vl_rts.xml';
if (file_exists($filexml)) {
    $xml = simplexml_load_file($filexml);
$f = fopen('vl_rts.csv', 'w');
foreach ($xml->Orders as $Orders) {
    fputcsv($f, get_object_vars($Orders),',','"');
}
fclose($f);
}
}

现在,我一开始并没有注意到 CSV 不包含任何 <OrderDetails> 标记中的数据。我是在开始做导入MySQL功能的时候才意识到这一点的。

因此,我没有倒退,而是继续前进,至少导入了 <Order> 数据:

function csvimport() { 
if(!file_exists("vl_rts.csv")) { echo "WARNING! CSV Not Found!<br>"; exit; }
$row = 0;
$mycsvfile = array();
if (($handle = fopen("vl_rts.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;
        for ($c=0; $c < $num; $c++) {
        }
        $mycsvfile[] = $data; //add the row to the main array.
    }
    fclose($handle);
}
echo "<br>Reading Rows:<br>";
//[row][column] so [1][$csvrow] = 2nd row, first column since 0=1
$csvrow = 0;
while ($mycsvfile[$csvrow][0] != $null) {
$query = mysql_query("SELECT * from vtiger_purchaseorder WHERE orderid=" . $mycsvfile[$csvrow][0]) or die(mysql_error());
if(mysql_num_rows($query)!=0)
{
//if row exists
$csvrow++;
echo "Row exists, changing rows...<br>";
echo "DO SOMETHING HERE, ANYTHING BUT THIS<br>"; //This is a "todo" spot for later
}
else //if row doesn't exist
{

$currentdate = date('Y-m-d');
$orderid = $mycsvfile[$csvrow][0];
$subject = "Uploading..."; //This is set to Uploading... now, in another function we'll come back change the subject to the name of the item sold.
$quoteid = $mycsvfile[$csvrow][0];
if ($mycsvfile[$csvrow][72] == 0) {
$vendorid = "1500"; //right now, new orders go into a temp vendor of 1500, then we'll change it based on the product ordered to see which vendor it should be assigned to.
echo "Vendor is " . $vendorid . "<br>";
$shipcity = "Shipcity"; This info is in <OrderDetails> which we don't have yet.

//This other database is vtiger, which has a lot of different area where it needs to store data, so here we insert it in a way vtiger can accept it.
$query1 = "SELECT * from vtiger_crmentity";
$query2 = "INSERT INTO vtiger_crmentity (smcreatorid,smownerid,modifiedby,setype,orderid) VALUES('1','1','1','PurchaseOrder','" . $orderid . "')";

$result1 = mysql_query($query1);
echo mysql_error() . "<br>";
$result2 = mysql_query($query2);
$crmid = mysql_insert_id();

$query3 = "SELECT * from vtiger_purchaseorder";
$query4 = "INSERT INTO vtiger_purchaseorder (purchaseorderid,subject,quoteid,vendorid,duedate,orderid) VALUES(" . $crmid . ",'" . $subject . "','" . $quoteid . "','" . $vendorid . "','" . $currentdate . "','" . $orderid . "')";

$query5 = "SELECT * from vtiger_poshipads";
$query6 = "INSERT INTO vtiger_poshipads (poshipaddressid,ship_city,orderid) VALUES(" . $crmid . ",'" . $shipcity . "','" . $orderid . "')";

echo mysql_error() . "<br>";
$result3 = mysql_query($query3);
echo mysql_error() . "<br>";
$result4 = mysql_query($query4);
echo mysql_error() . "<br>";
$result5 = mysql_query($query5);
echo mysql_error() . "<br>";
$result6 = mysql_query($query6);
echo mysql_error() . "<br>";
echo "CRMID " . $crmid . "<br>";

$csvrow++;
echo "Order doesn't exist, inserting order number " . $orderid . " from CSV row " . $csvrow . "<br>";
//CHANGE ORDER FROM READY TO SHIP TO PENDING SHIPMENT ON OTHER SITE (to do)


}
} 
}
echo "Import Complete.<br>";

}

现在快速回顾一下。因此,我们已经从其他服务器中提取了 .XML 文件。我们已经从 <Orders> 中获取了所有内容(除了所有子项)并将其插入到 CSV 中,现在我们已经获取了 CSV 数据并将其插入到 MySQL DB 中以创建新的采购订单。

新采购订单已存在,但缺少 <OrderDetails> 标签中的数据。

我尝试将所有 <OrderDetails> 数据放入一个数组中,但我只获取第一个 <Order> 中的前两个标签。

理想情况下,我希望提取所有 <OrderDetails> 标签并将它们插入到另一个 CSV 文件中。从那里我将使用与上面相同的方法将其拉出并插入。我已经尝试过此操作,但 CSV 已关闭,行未对齐,而且我仍然只获得前 2 个标签,而不是全部。

我对任何事情都持开放态度,所以请告诉我......

最佳答案

您应该直接处理 XML。尝试将数据转换为 CSV 文件会丢失数据的层次结构。

您可以使用SimpleXML读取所有数据。它看起来像这样:

$xml = new SimpleXMLElement($content);
foreach ($xml->Orders as $order) {
  $order_id = $order->OrderId;
  $order_status = $order->OrderStatus;

  // Here we have a single order
  // You can insert this order into the database

  foreach ($order->OrderDetails as $order_details) {
    $order_detail_id = $order_details->OrderDetailID;
    $product_id = $order_details->ProductID;

    // Here we have a single order detail that belongs to $order_id
    // You can insert this order detail into the database
  }
}

关于php - 将 XML 导入 MySQL,无法获取所有子标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10076970/

相关文章:

php - php 中针对连接查询返回 SQL 错误

mysql - ORDER BY RAND() 在 UNION 中不起作用

c# - XDocument 错误名称不能以 '<' 字符开头,十六进制值 0x3C

xml - 将每个计数器值从一个传递到另一个

php - 不使用 wp_die 向用户显示警告/错误

php - 在php中获取选择框值

PHP curl 调用 Web 服务 1 亿次

MySQL 测试数据库失败

php - 循环遍历表 mySQL 中的所有项目

android - Android Studio 中的 color.xml 文件出现奇怪的错误