Reputation: 25
I'm a game writer and designer and we use XML files for our dialogue engine. I'm trying to display the dialogue on a website for my team to see, and I'd like to be able to dynamically display certain parts or 'chapters' of the XML based on a URL variable. I'm using PHP for this.
Here is a very simple example of how our XML is structured:
<dialogues>
<dialogue id="0">
<line id="0_1" name="John">Line 1</line>
<line id="0_2" name="Eric">Line 2</line>
<line id="0_3" name="Ben">Line 3</line>
</dialogue>
<dialogue id="1">
<line id="1_1" name="Sarah">Line 1</line>
<line id="1_2" name="Jessica">Line 2</line>
<line id="1_3" name="Kelly">Line 3</line>
</dialogue>
</dialogues>
What I'd like to do is display the lines of specific dialogue
blocks based on a variable I pass through the URL. Here is my PHP so far.
$url = "dialogues.xml";
$xml = simplexml_load_file($url);
$chapter = $_GET['c'];
foreach($xml->dialogue->line as $dialogue)
{
echo '<p class="id">id: ' . $dialogue["id"] . '</p>';
echo '<p class="name">' . $dialogue["name"] . '</p>';
echo $dialogue."<br/>";
}
So you can see that I've got a $chapter
variable that I would get with ?c=
in the URL, I just don't know what to do from there. What I would do to this code to only display, say, the lines within <dialogue id="1">
based on ?c=1
in the URL?
Upvotes: 2
Views: 185
Reputation: 2962
Try using xpath; it's designed for this sort of situation. Here's an example of how to get each line of dialogue.
foreach ($xml->xpath("//dialogue[@*])/line") as $line)
echo $line;
Here's a helpful reference sourcce https://developer.mozilla.org/en-US/docs/Web/XPath
Upvotes: 2