0

I m just a beginner in PHP. Just want to make sure what I am doing is correct or am i complicating things or is there is any alternative in ajax

I have to read an xml file in php and store it in an array for further evaluation

The XML File is

> <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>

The PHP code for reading this data is

$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;  } }

Thanks in advance

3
  • Please format your code. Commented May 30, 2012 at 8:44
  • Sorry, cannot execute your example. The XML data as posted is invalid (mixed up nodes, no root element). Your code yields syntax error. Commented May 30, 2012 at 10:15
  • plz check now..i have reposted it Commented May 30, 2012 at 11:24

1 Answer 1

2

I usually use php SimpleXML for this purpose:

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

It can read xml structure from string and returns nice object.

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.