xml foreach在数据库中插入多个子节点

时间:2015-11-16 08:40:08

标签: php sql xml

我在使用xml foreach时出现问题,我需要将多个子节点输入数据库

所以对于xml部分

<Pieces>
    <Piece>
        <PieceNumber>1</PieceNumber>
        <Depth>5</Depth>
        <Width>5</Width>
        <Height>5</Height>
        <Weight>1</Weight>
        <PackageType>PA</PackageType>
        <DimWeight>0.025000</DimWeight>
        <DataIdentifier>J</DataIdentifier>
        <LicensePlate>JD014600002433049632</LicensePlate>
        <LicensePlateBarCode>iVBORw0KGgoAAAANSUhEUgAAAZYAAABeAQMAAAA6+qC4AAAABlBMVEX///8AAABVwtN+AAAAaElEQVR42u3LIRJAQBiA0Z9AUqStextHUSTJCMRVzFDYYLiNO2whklSNM2jC9/rzRKSIymk3eaXXOqzjI5jvZnDipaLax6klUVenV5vZcDy33oj48h2Hw+FwOBwOh8PhcDgcDofzp/MC4ZwWvNbw1agAAAAASUVORK5CYII=</LicensePlateBarCode>
    </Piece>
    <Piece>
        <PieceNumber>2</PieceNumber>
        <Depth>5</Depth>
        <Width>5</Width>
        <Height>5</Height>
        <Weight>1</Weight>
        <PackageType>PA</PackageType>
        <DimWeight>0.025000</DimWeight>
        <DataIdentifier>J</DataIdentifier>
        <LicensePlate>JD014600002433049633</LicensePlate>
        <LicensePlateBarCode>iVBORw0KGgoAAAANSUhEUgAAAZYAAABeAQMAAAA6+qC4AAAABlBMVEX///8AAABVwtN+AAAAaElEQVR42u3LIRJAQBiA0X83kBRpi+A2jkKWdoSVzCpmKJLhNu6gEDVV4wya8L3+lIjYqJoOX7p0rcM6PoP5bsdNVC6mezazZObqU9ecVifFPngRLd9xOBwOh8PhcDgcDofD4XA4fzov9XcVvFOzTc8AAAAASUVORK5CYII=</LicensePlateBarCode>
    </Piece>
</Pieces>

我要输入两个值

当我使用下面的内容时,我得到两次相同的值

//将片段输入数据库

foreach ($xml->Pieces->children() as $plate)
{
    $pl = $xml->Pieces->Piece->LicensePlate;
    $query4 = "INSERT INTO pieceplates" 
            . " ( waybill, plate ) " 
            . " VALUES ('$Waybill', '$pl')"; 
            //execute the query 
    $result4 = mysql_query($query4) 
    or die("There has been a problem entering pieces.");
    $pl = $xml->Pieces->Piece->LicensePlate;
}

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

我假设你使用的是SimpleXML,试试这个:

$xml = simplexml_load_string($pieces_xml);
foreach ($xml as $piece)
{
    $pl = $piece->LicensePlate;
    $query4 = "INSERT INTO pieceplates"
        . " ( waybill, plate ) "
        . " VALUES ('$Waybill', '$pl')";

    //execute the query
    $result4 = mysql_query($query4)
    or die("There has been a problem entering pieces.");
}

mysql_query() btw。自PHP 5.5起已被弃用,应由mysqli_query()替换。