PHP and XML XPath (New to this)

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
KBC
Forum Newbie
Posts: 6
Joined: Mon Aug 07, 2006 12:34 pm

PHP and XML XPath (New to this)

Post by KBC »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hi,

I've currently got a webpage which processes some information from an XML document.

OK, I've loaded the XML document like so...

[syntax="xml"]<?xml version="1.0" encoding="ISO-8859-1"?>
<gallery>
  <photo>
    <file>08.gif</file>
    <caption>Something</caption>
  </photo>
  <photo>
    <file>09.gif</file>
    <caption>Something</caption>
  </photo>
  <photo>
    <file>10.gif</file>
    <caption>Something!</caption>
  </photo>  
</gallery>
[/syntax]

Code: Select all

$dom = new DomDocument();
$dom -> load("xml/gallery.xml");
$xp = new DomXPath($dom);
$count = //query and retrieve count.
But as I'm quite new to both PHP and XPath, I need to need to be able to retrieve a count of all the nodes and store it in a variable...

So in the above XML document, I'd need it to return "3" because there are 3 <photo> nodes.

Also is there a way of being able to retrieve an index value of a particular node? So say if I pass a value "10.gif" into a function, it would return an index of "3" because it's the 3rd <photo> node under the element <gallery>.

That way I am able to use the index value and compare it to "count" to determine if I've reached the end of the XML document.

If there's an easier way, please tell me. As I'm new to this whole thing. :)


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Consult your xpath tutorial/reference and lookup the count and foreach keywords...

Here is an example that would generate <li> tags when there are at least 1 (more than 0) photos...

Code: Select all

<xsl:if test="count(gallery/photo) > 0">
      <ul>
        <xsl:for-each select="gallery/photo">
        <li><a href="{file}"><xsl:value-of select="caption"/></a></li>
        </xsl:for-each>
      </ul>
</xsl:if>
Post Reply