I am kinda new in XML but I can handle some things. Below there is a code that gets value from a HTML form and then displays some info from a XML file (see below). The code shows correctly all the info (TITLE, BAND, YEAR), but my question is how can I display also the id attribute of <CD id="XXX">
. Thank you!
the code
<?php
$q=$_GET["q"];
$xmlDoc = new DOMDocument();
$xmlDoc->load("database.xml");
$x=$xmlDoc->getElementsByTagName('TITLE');
for ($i=0; $i<=$x->length-1; $i++)
{
//Process only element nodes
if ($x->item($i)->nodeType==1)
{
if ($x->item($i)->childNodes->item(0)->nodeValue == $q)
{
$y=($x->item($i)->parentNode);
}
}
}
$cd=($y->childNodes);
for ($i=0;$i<$cd->length;$i++)
{
//Process only element nodes
if ($cd->item($i)->nodeType==1)
{
echo("<b>" . $cd->item($i)->nodeName . ":</b> ");
echo($cd->item($i)->childNodes->item(0)->nodeValue);
echo("<br />");
}
}
?>
XML
<CATEGORIES>
<CD id="1">
<TITLE>NEVER MIND THE BOLLOCKS</TITLE>
<BAND>SEX PISTOLS</BAND>
<YEAR>1977</YEAR>
</CD>
<CD id="2">
<TITLE>NEVERMIND</TITLE>
<BAND>NIRVANA</BAND>
<YEAR>1991</YEAR>
</CD>
</CATEGORIES>
First, it would be nicer to do this searching using XPath. The query to find a TITLE
element that have the content foo
is //TITLE[.="foo"]
. You can then use DOMElement::getAttribute
to get the attribute you want. So your code could look something like this:
$dom = new DOMDocument;
$dom->load("database.xml");
$xpath = new DOMXPath($dom);
$el = $xpath->query('//TITLE[.="' . $q . '"]');
if ($el->length) {
$cd = $el->item(0)->parentNode;
echo "<b>ID:</b> " . $cd->getAttribute('id');
foreach ($cd->childNodes as $node) {
if ($node->nodeType == 1) {
echo("<b>" . $node->nodeName . ":</b> ");
echo($node->nodeValue);
echo("<br />");
}
}
}
You can retreive a DomNode's attributes by calling $node->attributes().
For more information see this function's documentation: http://php.net/manual/en/function.domnode-attributes.php
A simpler way of dealing with XML is to use SimpleXML like this:
$xml = simplexml_load_file('database.xml');
foreach ($xml as $cd) {
echo 'ID: ' . $cd['id'] . '<br>';
echo 'Title: ' . $cd->TITLE . '<br>';
echo 'Band: ' . $cd->BAND . '<br>';
echo 'Year: ' . $cd->YEAR . '<br>';
}
You can use the DOMElement::getAttribute() method, so in your example:
echo $cd->item($i)->getAttribute("id");
Refer to the API http://www.php.net/manual/en/domelement.getattribute.php