使用PHP将XML导入MySQL只获取第一个子数据

时间:2017-11-03 02:41:43

标签: php mysql xml

经过多次试验和错误,我终于将我的PHP代码导入MySQL中。唯一的问题,它只从第一个子节点获取数据。

我的XML数据是这样构建的;

<Machine>
    <Stem>
        <Log>
            <ProductKey>1713</ProductKey>
            <LogVolume logVolumeCategory="m3sub" logMeasurementCategory="Machine">0.5682</LogVolume>
            <LogMeasurement logMeasurementCategory="Machine">
                <LogLength>551</LogLength>
            </LogMeasurement>
         </Log>
        <Log>
            <ProductKey>1713</ProductKey>
            <LogVolume logVolumeCategory="m3sub" logMeasurementCategory="Machine">0.5682</LogVolume>
            <LogMeasurement logMeasurementCategory="Machine">
                <LogLength>551</LogLength>
            </LogMeasurement>
         </Log>
        <Log>
            <ProductKey>1713</ProductKey>
            <LogVolume logVolumeCategory="m3sub" logMeasurementCategory="Machine">0.5682</LogVolume>
            <LogMeasurement logMeasurementCategory="Machine">
                <LogLength>551</LogLength>
            </LogMeasurement>
         </Log>
    </Stem>
    <Stem>
        <Log>
            <ProductKey>1713</ProductKey>
            <LogVolume logVolumeCategory="m3sub" logMeasurementCategory="Machine">0.5682</LogVolume>
            <LogMeasurement logMeasurementCategory="Machine">
                <LogLength>551</LogLength>
            </LogMeasurement>
         </Log>
        <Log>
            <ProductKey>1713</ProductKey>
            <LogVolume logVolumeCategory="m3sub" logMeasurementCategory="Machine">0.5682</LogVolume>
            <LogMeasurement logMeasurementCategory="Machine">
                <LogLength>551</LogLength>
            </LogMeasurement>
         </Log>
        <Log>
            <ProductKey>1713</ProductKey>
            <LogVolume logVolumeCategory="m3sub" logMeasurementCategory="Machine">0.5682</LogVolume>
            <LogMeasurement logMeasurementCategory="Machine">
                <LogLength>551</LogLength>
            </LogMeasurement>
         </Log>
    </Stem>
</Machine>

PHP;

foreach($data->Stem as $Stem)
    {
        $statement->execute(
            array(
            ':productkey'    => $Stem->SingleTreeProcessedStem->Log->ProductKey,
            ':logvolume'     => $Stem->SingleTreeProcessedStem->Log->LogVolume[1],
            ':loglength'     => $Stem->SingleTreeProcessedStem->Log->LogMeasurement->LogLength
            )
        );

    }

目前,这是循环遍历所有 Stem 标记并获取第一个 Log 标记的信息。 我需要它来从所有日志标记中获取信息。 我试图改写我的foreach声明,但是我还是新手,所以我希望有人可以告诉我哪里出错了?

1 个答案:

答案 0 :(得分:0)

您还需要一个foreach循环:

foreach($data->Stem as $Stem)
{
    foreach($Stem->Log as $Log) {
        $statement->execute(
            array(
                ':productkey'    => $Stem->SingleTreeProcessedStem->Log->ProductKey,
                ':logvolume'     => $Stem->SingleTreeProcessedStem->Log->LogVolume[1],
                ':loglength'     => $Stem->SingleTreeProcessedStem->Log->LogMeasurement->LogLength
            )
        );
    }
}