开发者

Searching an XML file using PHP [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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 sy开发者_运维知识库mbol 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';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜