Displaying just one node using simplexml and GET

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
benbr
Forum Newbie
Posts: 3
Joined: Sun May 22, 2005 5:14 pm
Location: Boston, MA

Displaying just one node using simplexml and GET

Post by benbr »

I'm trying to use PHP to display the contents of an XML document. I had no trouble creating a page that listed all of the items in my XML file. But what I want to do is create pages that display information from just one of the nodes in the XML file, using a URL like this: test.php?itemID=0

Code: Select all

<?php 
ini_set('error_reporting', E_ALL);
ini_set('display_errors', TRUE); 

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<tests>
<test>
    <testtitle id=&quote;1&quote;>I want to show this one.</testtitle>
    <testtitle id=&quote;2&quote;>Not this one.</testtitle>
</test>
</tests>
XML;

$xml = simplexml_load_string($xmlstr);
$itemID =$_GETї&quote;itemID&quote;];
$test=$xml->testї0];
?>
<p>Show <?php echo $itemID;?></p>
<p>Title: <?php echo $test->testtitleї$itemID]; ?></p>
That displays this:

Code: Select all

Show 0
Title:
If I change '$itemID' to '0' in the last line, then the script does what it should:

Code: Select all

Show 0
Title: I want to show this one.
What am I doing wrong? I don't get any errors. How do I select a specific node using a variable? I've been combing through the PHP manual, and googling 'simplexml' but I can't find the answer.
User avatar
benbr
Forum Newbie
Posts: 3
Joined: Sun May 22, 2005 5:14 pm
Location: Boston, MA

Post by benbr »

OK, I figured it out. I had to set the value of the GET variable to be an integer. Like so (see line 16):

Code: Select all

<?php 
ini_set('error_reporting', E_ALL);
ini_set('display_errors', TRUE); 

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<tests>
<test>
    <testtitle id="1">I want to show this one.</testtitle>
    <testtitle id="2">Not this one.</testtitle>
</test>
</tests>
XML;

$xml = simplexml_load_string($xmlstr);
//which test title?
$itemID=intval($_GET["itemID"]);
$test=$xml->test[0];
?>
<p>Show <?php echo $itemID;?></p>
<p>Title: <?php echo $test->testtitle[$itemID]; ?></p>
Once I did that I was good to go.
Post Reply