使用PHP搜索XML文件[关闭]

I have an XML file like this:

<quotes>
  <quote>
    <symbol>7UP</symbol>
    <change>0</change>
    <close>45</close>
    <date>2011-08-24</date>
    <high>45</high>
  </quote>
</quotes>

I want to search this document by symbol and obtain the matching close value, in PHP.

Thanks.

Use XPath.

Using SimpleXML:

$sxml = new SimpleXMLElement($xml);
$close = $sxml->xpath('//quote[symbol="7UP"]/close/text()');
echo reset($close); // 45

Using DOM:

$dom = new DOMDocument;
$dom->loadXML($xml);
$xpath = new DOMXPath($dom);
$close = $xpath->query('//quote[symbol="7UP"]/close/text()')->item(0)->nodeValue;
echo $close;        // 45

...for numeric values specifically, with DOM, you can do (as suggested by @fireeyedboy):

$close = $xpath->evaluate('number(//quotes/quote[symbol="7UP"]/close/text())');
echo $close;        // 45

You can just parse your XML file to an object or an array. Makes it a lot easier to work with in PHP. PHP has simpleXML for this, which is enabled by default:

http://www.php.net/manual/en/simplexml.installation.php

Example:

$xml = new SimpleXMLElement($xmlstr);

foreach ($xml->quotes->quote as $quote) 
{
  // Filter the symbol
  echo ( (string) $quote->symbol === '7UP') 
    ? $quote->close 
    : 'something else';
}