[英]Insert XML Data to MySQL Table Using PHP
我正在嘗試將xml數據插入到我的sql中,但是沒有插入。 如何為這種類型的xml編寫foreach(xml->)。xml是在此結構中動態生成的。這是這種格式的示例xml
<?php
$xmlData =<<< END
<?xml version="1.0"?>
<Customer>
<id>1</id>
<name>Oluwafemi</name>
<address>Cresent Drive, TX</address>
<list>
<contact>56689</contact>
<telephone>5889745</telephone>
</list>
<offer>congrats</offer>
</Customer>
END;
$xml = simplexml_load_string($xmlData) or die("ERROR: Cannot create SimpleXML object");
$connection = mysqli_connect("localhost", "root", "", "Customers") or die ("ERROR: Cannot connect");
foreach ($xml->Customer as $Customer) {
$id = $Customer->id;
echo "$id";
$name = $Customer->name;
$address = $Customer->address;
$sql = "INSERT INTO customerdata (id, name, address ) VALUES ('$id', '$name', '$address')";
mysqli_query($connection, $sql) or die ("ERROR: " .mysqli_error($connection) . " (query was $sql)");
}
mysqli_close($connection);
?>
假設您有多個客戶...
$sXmlString =<<< END
<?xml version="1.0"?>
<Content>
<Customer>
<id>1</id>
<name>Oluwafemi</name>
<address>Cresent Drive, TX</address>
</Customer>
<Customer>
<id>2</id>
<name>Oluwafemi2</name>
<address>Cresent Drive 2, TX</address>
</Customer>
</Content>
END;
$oXml = simplexml_load_string($sXmlString);
$sJson = json_encode( $oXml );
$aContent = json_decode( $sJson, TRUE );
$aCustomers = $aContent[ 'Customer' ];
var_dump( $aCustomers );
$iCountCustomers = count( $aCustomers );
for( $i = 0; $i < $iCountCustomers; ++$i )
{
$sId = $aCustomers[ $i ][ 'id' ];
$sName = $aCustomers[ $i ][ 'name' ];
$sAddress = $aCustomers[ $i ][ 'address' ];
var_dump( $sId );
var_dump( $sName );
var_dump( $sAddress );
}
您需要編輯XML文檔,並使用以下標記封裝文檔:
<Customers> ... </Customers>
因此,代碼的開始部分應如下所示:
<?xml version="1.0"?>
$sXmlString =<<< END
<Customers>
<Customer>
<id>1</id>
<name>Oluwafemi</name>
<address>Cresent Drive, TX</address>
</Customer>
</Customers>
END;
編輯:OP無法編輯提供的XML,我認為它的結構是在其中添加新客戶,附加ID,名稱,地址實體的結構中。 這是OP的更新代碼:
<?php
$xmlData =<<< END
<?xml version="1.0"?>
<Customer>
<id>1</id>
<name>Oluwafemi</name>
<address>Cresent Drive, TX</address>
<id>2</id>
<name>Rob</name>
<address> 123 Longhorn </address>
</Customer>
END;
$xml = simplexml_load_string($xmlData) or die("ERROR: Cannot create SimpleXML object");
$connection = mysqli_connect("localhost", "root", "", "Customers") or die ("ERROR: Cannot connect");
/* Assumes that the number of IDs = number of customers */
$size = sizeOf($xml->id);
$i = 0; //index
/* Add each customer to the database, See how we reference it as $xml->ENTITY[INDEX] */
while($i != $size)
{
//echo $xml->id[$i]; //Test
$sql = "INSERT INTO customerdata (id, name, address ) VALUES ('$xml->id[$i]', '$xml->name[$i]', '$xml->address[$i]')";
mysqli_query($connection, $sql) or die ("ERROR: " .mysqli_error($connection) . " (query was $sql)");
$i++; //increment index
}
mysqli_close($connection);
我還添加了帶有數據的其他客戶ID。 您可以刪除它,代碼仍然可以正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.