I started mixing XML with PHP today and I'm pretty bad at it, even though it looks super simple.
Right now, I'm trying to make something that sounds very easy but I can't understand how it works. I'm basically trying to create a fake mailbox for a game.
So I stored my emails in an XML file, classed by categories (received, sent, etc.). I managed to get the list of emails depending on the category, but I can't get to the part where I click on an email and it shows the content of this particular email.
Here is my simplified code:
XML :
<mailbox>
<received>
<expediter>James</expediter>
<content>Blah blah blah</content>
</received>
<received>
<expediter>Paul</expediter>
<content>Bluh bluh bluh</content>
</received>
<sent>
<expediter>Jack</expediter>
<content>Blah blah blah</content>
</sent>
<sent>
<expediter>John</expediter>
<content>Bluh bluh bluh</content>
</sent>
</mailbox>
XML;
?>
PHP :
<?php
include 'emails.php';
$emails = new SimpleXMLElement($xmlstr);
$cat = $_GET['cat'];
if(!isset($_GET['id'])){
$i = 0;
foreach($emails->$cat as $mailbox){
echo '<a href="?page=mailbox&cat='.$cat.'&id='.$i.'">'.$mailbox->expediter.'</a><br />';
$i++;
}
}
else{
$id = $_GET['id'];
echo $emails->$cat[$id]->content;
}
?>
So if there is no ID in the url, it shows the list of expediters with links to the email and if there is an ID in the url, it should show the content of the email designed by this number.
It works if I write manually :
echo $emails->received[1]->content;
But of course, I want that part to be dynamic and it doesn't work with :
echo $emails->$cat[$id]->content;
Is there any way to do that?
Thank you!
Camille
Try this:
$a = new stdClass();
$b = new stdClass();
$b->field = 5;
$a->list = array(
1 => $b
);
print_r($a);
$param = 'list';
$id = 1;
print_r($a->list[1]->field); // outputs 5;
print_r($a->{$param}[$id]->field); // outputs 5;
The key is:
$a->{$param}[$id]->field // notice the curly brackets.
Adapting to your question, you should use:
echo $emails->{$cat}[$id]->contenu;
As a good practice, you might want to check if it exists first:
if(isset($emails->{$cat}[$id])){
// echo it here, after you know it exists
}
You can see it online at 3v4l example