讲代码
$xchange = new SimpleXMLElement('http://www.bankisrael.gov.il/currency.xml', NULL, TRUE);
$filterCurrencies = array( 'USD', 'GBP' );
$filter = implode( array_map( function($filler) { return 'text()="'.$filler.'"'; }, $filterCurrencies), ' or ' );
$xpathQuery = $xpath = '//CURRENCYCODE[%filter%]/parent::*';
$xpathQuery = str_replace('%filter%', , $xpathQuery);
$currencies = $xchange->xpath($xpathQuery);
/** I do know you already have to code to echo it ... the code is tested, feel free to copy&pase **/
一步一步
好的,首先,您使用 SimpleXML 对象从以色列银行读取数据。我建议利用这个对象来完成大部分工作(这比使用 PHP 过滤要快得多,尽管 SimpleXML 并不是最好的性能)。
那么首先我们想要完成什么?
根据元素的内容获取 a 的数据。
对于网页设计师来说,这听起来应该像 CSS,但并不完全正确。对于拥有听起来像 XPath 的 XML 的 Web 开发人员来说,这是最佳选择!
幸运的是,SimpleXML 使我们能够使用 XPath,因此我们将构建一个查询:
XPath 基础知识:
//CURRENCYCODE 将选择任何货币代码元素
//CURRENCYCODE/parent::* 将选择货币代码父级 (<CURRENCY>),这是我们的数据所在的位置
//CURRENCYCODE[text()="JPY"] 将只选择文本正好等于 JPY 的 <CURRENCY> 元素。
在这里,我们用我们的需求列表来加盐:
$filterCurrencies = array( 'USD', 'GBP' ); // we want us dollars and british pounds
$filter = implode( array_map( function($token) { return 'text()="'.$token.'"'; }, $filterCurrencies), ' or ' );
// this will make a string like 'text()="USD" or text()="GBP"' by mapping the filter against the requirements string (currenciecodes get tokens) glueing it with a logical or
现在唯一要做的就是将它与我们的 XPATH 模板集成
$xpath = '//CURRENCY[%filter%]/parent::*';
$xpath = str_replace('%filter%', $filter, $xpath);
$currencies = $xchange->xpath($xpath);
循环愉快!