2011-08-25 74 views
2

一個XML文件,我有一個這樣的XML文件:搜索使用PHP

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

我想symbol這份文件搜索並獲取匹配close值,在PHP。

謝謝。

+1

你是什麼意思'基於「符號」'? 注意:如果可能的話,不會傷害提高您的接受評級。 – Pete171

+0

[使用XPath匹配基於兄弟值的節點]的可能重複(http://stackoverflow.com/questions/912194/matching-a-node-based-on-a-siblings-value-with-xpath) –

+0

我不知道'基於'符號''是什麼意思。 – TRiG

回答

7

使用XPath。

使用SimpleXML:

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

使用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 

...的具體數值,與DOM,你可以做的(由@fireeyedboy的建議):

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

+1好的答案。我會發佈一個替代方案,但是如果您喜歡,可以將其添加到您的答案中:'$ close = $ xpath-> evaluate('number(/ quotes/quote [symbol =「7UP」] [1]/close/text())');'(當然是DOMXPath) –

+0

完成。感謝您的建議。 – netcoder

+0

這裏是我的代碼,bur我有錯誤'公共函數getStock($符號) \t { \t \t $ api = file_get_contents(「http://stocks.com」); \t \t $ sxml = new SimpleXMLElement($ api); \t \t $ close = $ sxml-> xpath(「// quote [symbol =」。$ symbol。「]/close/text()」); \t \t return reset($ close); // 45 \t}' – Cyberomin

1

您可以將您的XML文件解析爲對象或數組。在PHP中使用起來更容易。 PHP有simpleXML對於這一點,這是默認啓用:

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

例子:

$xml = new SimpleXMLElement($xmlstr); 

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