繁体   English   中英

我无法使用php从xml文件中获取所有数据

[英]I can't get all the data from an xml file with php

除了所有<Item>数据之外,我还可以从xml中获取数据。 下面的代码仅获取最后一个的数据。 我以为foreach会为每个人都做到这一点,但事实并非如此。

<magic5Out version="2.1.0">
<Report customerPK="Survey_2" locationPK="229" userId="2299" template="13600" formDate="2012-04-11T00:00:00" dateTimeStarted="2012-04-11T07:34:04" dateTimeMobileReleased="2012-04-11T07:37:03" currentStatus="5" reportGuid="b174d011-77bb-4882-b87e-a2c60bdf265d">
    <Results>
        <Item itemPK="SurveyTab_9">
            <q1 listEntry="1.8m" listEntryId="239107"/>
            <q1Comments text=""/>
            <q2 listEntry="Green" listEntryId="239113"/>
            <q2Comments text=""/>
            <item_comments text="test"/>
        </Item>
        <Item itemPK="SurveyTab_24">
            <q1 listEntry="2.2m" listEntryId="239108"/>
            <q1Comments text=""/>
            <q2 listEntry="Silver" listEntryId="239112"/>
            <q2Comments text=""/>
            <item_comments text=""/>
        </Item>
        <Item itemPK="SurveyTab_10">
            <q1 listEntry="3.0m" listEntryId="239110"/>
            <q1Comments text=""/>
            <q2 listEntry="White" listEntryId="239111"/>
            <q2Comments text=""/>
            <item_comments text="No feed"/>
        </Item>
        <Item itemPK="SurveyTab_23">
            <q1 listEntry="2.2m" listEntryId="239108"/>
            <q1Comments text=""/>
            <q2 listEntry="Green" listEntryId="239113"/>
            <q2Comments text=""/>
            <item_comments text=""/>
        </Item>
    <surveyorComments0 text="testing"/>
    <surveyorName text="NICK"/>
    <surveyorSig opFile="D:\Sites\WebApp_eden\Output\2100\XMLSurvey\Attachments\1cf582f9-776c-472e-b8ce-877a51fae5e1.png"/>
    </Results>
</Report>
</magic5Out>

这是我正在使用的php:

$xml = simplexml_load_file($xml_file); 
/* more code here that works OK */
foreach($xml->Report->Results->Item as $tab) {
    $tab_name = (string) $tab['itemPK'];
    $q1_result =  $tab->q1['listEntry'];
    $q2_result =  $tab->q2['listEntry'];  etc.
    $q1_comment =  escape_data($tab->q1Comments['text']);
    $q2_comment =  escape_data($tab->q2Comments['text']);
    $item_comment = escape_data($tab->item_comments['text']);
}

进行循环并定义变量时,变量中将包含循环中的最后一个值。

您每次都会覆盖变量。

foreach($xml->Report->Results->Item as $tab) {
    $tab_name[] = (string) $tab['itemPK'];
    $q1_result[] =  $tab->q1['listEntry'];
    $q2_result[] =  $tab->q2['listEntry'];  etc.
    $q1_comment[] =  escape_data($tab->q1Comments['text']);
    $q2_comment[] =  escape_data($tab->q2Comments['text']);
    $item_comment[] = escape_data($tab->item_comments['text']);
}

尝试这样的事情。 然后,您将获得一个包含所有值的数组。

在代码中肯定有其他地方在搞砸了-我尝试了很多其他事情,最终恢复到我上面发布的php,这一次起作用了。 希望那只是我自己的时间,我浪费在这上面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM