我无法使用 php 从 xml 文件中获取所有数据
问题描述:
除了所有的
I can get the data from the xml apart from all the <Item> data. The code below only gets the data for the last one. I thought the foreach would get it for each of them but it doesn't seem to.
<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:
here's the php I'm using:
$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']);
}
答
当您创建一个循环并定义一个变量时,在您的情况下,您的变量中就有了循环中的最后一个值.
When you make a loop and define a variable then you have in your case the last value from the loop in your variable.
你每次都覆盖你的变量.
You overwrite your variable everytime.
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']);
}
尝试这样的事情.然后你就有了一个包含所有值的数组.
try something like this. Then you have an array with all the values.