在PHP中读取XML文件并将值存储在数组中

时间:2012-05-30 08:42:54

标签: php xml

我只是PHP的初学者。只是想确保我正在做的事情是正确的还是让事情变得复杂,或者是否在ajax中有任何替代方案

我必须在php中读取一个xml文件并将其存储在一个数组中以供进一步评估

XML文件

> <IntervalReading>
>     <cost>907</cost>
>     <timePeriod>
>         <duration>900</duration>
>         <start>1330580700</start>
>          <!-- 3/1/2012 5:45:00 AM  -->
>     </timePeriod>
>     <value>302</value> </IntervalReading> <IntervalReading>
>     <cost>907</cost>
>     <timePeriod>
>         <duration>900</duration>
>         <start>1330581600</start>
>          <!-- 3/1/2012 6:00:00 AM  -->
>     </timePeriod>
>     <value>302</value> </IntervalReading> <IntervalReading>
>     <cost>907</cost>
>     <timePeriod>
>         <duration>900</duration>
>         <start>1330582500</start>
>          <!-- 3/1/2012 6:15:00 AM  -->
>     </timePeriod>
>     <value>302</value> </IntervalReading>

用于读取此数据的PHP代码是

$doc = new DOMDocument(); $doc->load( "tmp/".$filename ); $employees = array(); $value = array(); $cost =         array(); $start =     array();    $duration = array(); $doc->formatOutput = true; $employees = $doc->getElementsByTagName( "IntervalReading" );    foreach( $employees as $employee )  {
    $names = $employee->getElementsByTagName( "value" ); 
    $val =  $value[] = $names->item(0)->nodeValue;
    $costs = $employee->getElementsByTagName( "cost" ); 
    $cost[] =  $costs->item(0)->nodeValue;  
    $startnames = $employee->getElementsByTagName( "start" ); 
    $start[] = $startnames  ->item(0)->nodeValue;
    $durations  = $employee->getElementsByTagName( "duration" );
    $duration[] = $durations->item(0)->nodeValue;  } }

提前致谢

1 个答案:

答案 0 :(得分:2)

我通常使用php SimpleXML来实现此目的:

http://php.net/manual/en/book.simplexml.php

它可以从字符串中读取xml结构并返回漂亮的对象。

相关问题