1

I have an XML file which I receive by post.

<response>
       <id>D234>/id>
       <Logs>
          <time>UTC</time>
          <Alarms>          
          </Alarms>
       </Logs>
</response>

Sometimes it may have few alarm logs

<response>
   <id>D234>/id>
   <Logs>
    <time>UTC</time>
    <Alarms>
        <Log>
            <LD>Reset </LD>
            <utc>1383704429</utc>
        </Log>
        <Log>
            <LD>Triggered </LD>
            <utc>1383601449</utc>
        </Log>
    </Alarms>
    </Logs>
</response>

I want to check if <Alarms> has children, and then form a query to insert them into db. I tried xpath. I can find if children are there or not, and I can count. no problem.

$xml = simplexml_load_string(POST_DATA);
$alarms = $xml->xpath('Logs/Alarms');
echo count($alarms);

But how can traverse through each of the log? so that I can form a query to enter into DB. I am at a loss.

eg: how can I get Log0->time?

2 Answers 2

1

Try this:-

$alarms = $xml->xpath('Logs/Alarms/Log');
foreach ($alarms as $oneAlarm) {
    echo $oneAlarm->LD . "\n";
    echo $oneAlarm->utc . "\n";
}
Sign up to request clarification or add additional context in comments.

Comments

1

You have to alter the looping logic. Please find this php fiddle.

source code:

<?php

$xml = simplexml_load_string("<response><id>D234</id>
   <Logs>
    <time>UTC</time>
    <Alarms>
        <Log>
            <LD>Reset </LD>
            <utc>1383704429</utc>
        </Log>
        <Log>
            <LD>Triggered </LD>
            <utc>1383601449</utc>
        </Log>
    </Alarms>
    </Logs>
</response>");

$alarms = $xml->xpath('Logs/Alarms');


if (!empty($alarms)) {
    
   foreach ($alarms[0]->Log as $log) {
       
       echo $log->LD;
       echo $log->utc;
   
   }

}


?>

3 Comments

offcourse. Its what goes inside that is troubling me. I want to access each nodes inside the log node
thanks for the update. I am running xpath to get $alarms, and ->children() is not working on it. it throws an error. But Shazbot took me in the right direction. Appreciate it very much.
@aVC : No issues. Please check if it loops though the node values. If not, please refer to this, I have posted a working php fiddle with your xml data and code.

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.