How to display only the second item from XML with this PHP script?
<xml>
<item>
<name>Examplename</name>
<amount>0000</amount>
</item>
<item>
<name>Examplename</name>
<amount>0000</amount>
</item>
<item>
<name>Examplename</name>
<amount >0000</amount>
</item>
<item>
<name>DExamplename</name>
<amount>0000</amount>
</item>
</xml>
<?
// DOMElement->getElementsByTagName() -- Gets elements by tagname
// nodeValue : The value of this node, depending on its type.
// Load XML File. You can use loadXML if you wish to load XML data from a string
$objDOM = new DOMDocument();
$objDOM->load("feed.xml"); //make sure path is correct
$note = $objDOM->getElementsByTagName("item");
// for each note tag, parse the document and get values for
// tasks and details tag.
foreach( $note 开发者_StackOverflow社区as $value ){
$places = $value->getElementsByTagName("name");
$place = $places->item(0)->nodeValue;
$details = $value->getElementsByTagName("amount");
$detail = $details->item(0)->nodeValue;
echo "<BODY STYLE='background-color:transparent'>
<table border='0'>
<tr>
<td width='127'><table width='127px' border='0' cellpadding='0' cellspacing='0'>
<tr>
<td><p style='font-family:arial;color:white;font-size:22px;padding-left:3px;text-align:left; background:url(bg2.png)'><strong> $place</strong></p></td>
</tr>
</table>
</td>
<td width='115'>
<table width='115px' border='0' cellpadding='0' cellspacing='0'>
<tr>
<td><p style='font-family:arial;color:white;font-size:22px;text-align:right;padding-right:5px; background:url(bg1.png)'><strong>$detail</strong></p></td>
</tr>
</table></td>
</tr>
</table>
";
$i++; }
?>
You need to exploit XPath
Using SimpleXML:
<?php
$str = <<<STR
<?xml version="1.0" encoding="utf-8"?>
<XmlDoc>
<item>
text
</item>
<item>
text2
</item>
</XmlDoc>
STR;
$xml = simplexml_load_string($str);
$second_item = $xml->xpath('//item[2]'); // notice [2]!
var_export($second_item);
Using DOMDocument and DOMXPath:
<?php
$str = <<<STR
<?xml version="1.0" encoding="utf-8"?>
<xml>
<item>
<name>Examplename</name>
<amount>0000</amount>
</item>
<item>
<name>Examplename</name>
<amount>0000</amount>
</item>
<item>
<name>Examplename</name>
<amount >0000</amount>
</item>
<item>
<name>DExamplename</name>
<amount>0000</amount>
</item>
</xml>
STR;
$xml = DOMDocument::loadXML($str);
$xpath = new DOMXpath($xml);
$x = $xpath->query('//item[2]');
var_export($x->item(0)->nodeValue);
精彩评论