PDA

View Full Version : Writing only last object in xml



I am Abby
05-10-2010, 04:03 PM
I have a page that has a default message unless you change it. So when there's only one record in the xml you will see the default...but it you add a record the page will display that.

So I want my page to only print the last record in the xml.

The xml

<myusers>
<messages>
<id>1</id>
<message>words words and more words</message>
</messages>
</myusers>


<?php
$file = 'myxml.xml';
$xml = simplexml_load_file($file);

foreach($xml->children as messages)
{
$i = count ($xml->messages)-1;
echo $messages[$i]->message;
}
?>

I would thing this would print the last message only...but that's not what I'm getting.

I am Abby
05-11-2010, 01:36 PM
I tried


<?php
$file = 'myxml.xml';
$xml = simplexml_load_file($file);

$i = count($xml->messages)-1;
for($x=$i;$x>=0;$x--)
{
echo '
<hr>'
.$id.'<br />'
.$messages[$x]->message;
}
?>

which gives me a "<hr>" line across the page for every item in my xml. But I don't get anything in the xml printed out.

I am Abby
05-11-2010, 03:46 PM
I tried


<?php
$file = 'myxml.xml';
$xml = simplexml_load_file($file);

$i = count($xml->messages)-1;
for($x=$i;$x>=0;$x--)
{
echo '
<hr>'
.$id.'<br />'
.$messages[$x]->message;
}
?>
w

In case anyone else has this problem the answer is to use


echo '
<hr>'
.$xml->messages[$x]->id.'<br />'
.$xml->messages[$x]->message;
break;

the above will print the last item in your xml only.

Yea me!

katierosy
05-11-2010, 04:08 PM
If you will write like this, you may be able to see the result as expected.

<?php
$file = "myxml.xml";
$xml = simplexml_load_file($file);
$cnt = count($xml->messages);

for($i=0;$i<$cnt;$i++){

if($i==$cnt-2){
print $xml->messages[$i]->message;
}

}

?>

I am Abby
05-12-2010, 04:42 PM
[QUOTE=katierosy;226454]
if($i==$cnt-2)
QUOTE]

katierosy,
I'm not sure I understand this line...why -2 and not -1?