从 xml 中的特定可识别标签之间抓取

发布于 2024-11-05 11:47:55 字数 784 浏览 1 评论 0原文

我有以下内容来提取货币名称、货币代码、国家和汇率,问题是它获取所有货币,我只想获取某些货币,即仅获取美元、英镑和加元

<?php

$xchange = new SimpleXMLElement('http://www.bankisrael.gov.il/currency.xml', NULL, TRUE);

echo "
<table>
        <tr>
                <th>n</th>
                <th>cc</th>
                <th>c</th>
                <th>r</th>

        </tr>";

foreach($xchange as $curr) // loop through our books
{

        echo "
        <tr>
                <td>{$curr->NAME}</td>
                <td>{$curr->CURRENCYCODE}</td>
                <td>{$curr->COUNTRY}</td>
                <td>{$curr->RATE}</td>
        </tr>";
}

echo '</table>';
?>

i have the following to extract the currency name currency code country and rate, the problem is that it grabs all the currencies, i would like to only get certain currencies ie only the usd gbp and cad

<?php

$xchange = new SimpleXMLElement('http://www.bankisrael.gov.il/currency.xml', NULL, TRUE);

echo "
<table>
        <tr>
                <th>n</th>
                <th>cc</th>
                <th>c</th>
                <th>r</th>

        </tr>";

foreach($xchange as $curr) // loop through our books
{

        echo "
        <tr>
                <td>{$curr->NAME}</td>
                <td>{$curr->CURRENCYCODE}</td>
                <td>{$curr->COUNTRY}</td>
                <td>{$curr->RATE}</td>
        </tr>";
}

echo '</table>';
?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

夜清冷一曲。 2024-11-12 11:47:55

这段代码应该以更简洁的方式完成这项工作:

<?php

$a = getCurrencyData('http://www.bankisrael.gov.il/currency.xml');
print_r($a);

function getCurrencyData($url) {

    $raw = file_get_contents($url);
    $xml = new SimpleXMLElement($raw);

    $ret = array();

    foreach($xml->CURRENCY as $currency) {
        $currency = (array) $currency;
        $ret[$currency['CURRENCYCODE']] = $currency;
    }

    return $ret;
}

您现在可以通过使用货币代码来获取您想要的货币,例如 $a['GBP']

This piece of code should do the job in a much cleaner way:

<?php

$a = getCurrencyData('http://www.bankisrael.gov.il/currency.xml');
print_r($a);

function getCurrencyData($url) {

    $raw = file_get_contents($url);
    $xml = new SimpleXMLElement($raw);

    $ret = array();

    foreach($xml->CURRENCY as $currency) {
        $currency = (array) $currency;
        $ret[$currency['CURRENCYCODE']] = $currency;
    }

    return $ret;
}

You can now just get at the currencies you want by using the currency code e.g. $a['GBP']

两人的回忆 2024-11-12 11:47:55

这似乎工作得足够好:它过滤掉 $filter 中不存在的所有内容。如果在$filter中,就会显示出来。我已经测试过了,它似乎很有魅力。

<?php

/**
 * This is an array indicating which currencies you want to show.
 */
$filter = array(
    'usd',
    'gbp',
    'cad'
);

$root = simplexml_load_file( 'http://www.bankisrael.gov.il/currency.xml' );

echo "
<table>
    <tr>
        <th>n</th>
        <th>cc</th>
        <th>c</th>
        <th>r</th>
    </tr>\n";

foreach( $root->CURRENCY as $currency ) {
    if( in_array( (string) strtolower( $currency->CURRENCYCODE ), $filter ) ) {
        echo "
    <tr>
        <td>{$currency->NAME}</td>
        <td>{$currency->CURRENCYCODE}</td>
        <td>{$currency->COUNTRY}</td>
        <td>{$currency->RATE}</td>
    </tr>\n";
    }
}

echo "</table>\n";

This seems to work decently enough: it filters out everything that isn't in $filter. If it is in $filter, it will be displayed. I've tested it, and it seems to work like a charm.

<?php

/**
 * This is an array indicating which currencies you want to show.
 */
$filter = array(
    'usd',
    'gbp',
    'cad'
);

$root = simplexml_load_file( 'http://www.bankisrael.gov.il/currency.xml' );

echo "
<table>
    <tr>
        <th>n</th>
        <th>cc</th>
        <th>c</th>
        <th>r</th>
    </tr>\n";

foreach( $root->CURRENCY as $currency ) {
    if( in_array( (string) strtolower( $currency->CURRENCYCODE ), $filter ) ) {
        echo "
    <tr>
        <td>{$currency->NAME}</td>
        <td>{$currency->CURRENCYCODE}</td>
        <td>{$currency->COUNTRY}</td>
        <td>{$currency->RATE}</td>
    </tr>\n";
    }
}

echo "</table>\n";
℉絮湮 2024-11-12 11:47:55

用代码说话

$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 元素的内容获取 a 的数据。
对于网页设计师来说,这听起来应该像 CSS,但不太正确。对于拥有听起来像 XPath 的 XML 的 Web 开发人员来说,这是黄金选择!
幸运的是,SimpleXML 使我们能够使用 XPath,因此我们将构建一个查询:

XPath 基础知识
//CURRENCYCODE 将选择任何货币代码元素
//CURRENCYCODE/parent::* 将选择货币代码父级 (),这是我们的数据所在
//CURRENCYCODE[text()="JPY"] 将仅选择文本完全等于 JPY 的 元素。

在这里,我们对需求列表进行加盐:

$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);

快乐循环!

Code speaking

$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 **/

Step by Step

Okay, first of all, you're using a SimpleXML object to read in the data from bank israel. I suggest to leverage this object to do most of the work (which is much faster compared to filtering with PHP, although SimpleXML isn't the best thing for performance).

So first of all what do we want to accomplish?
Getting the Data of a based on the content of its element.
For an Webdesigner this should sound like CSS, but not quite right. For a web developer having his hands on an XML that should sound like XPath, which is the golden choice!
Fortunately, SimpleXML enables us to use XPath, so we'll build a query:

XPath basics:
//CURRENCYCODE will select any currencycode element
//CURRENCYCODE/parent::* will select the currencycodes parent (<CURRENCY>), which is where our data is
//CURRENCYCODE[text()="JPY"] will select only <CURRENCY> elements whose text equals JPY exactly.

Here we salt with our requirementslist:

$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

Now the only thing left to do is to integrate that with our XPATH template

$xpath = '//CURRENCY[%filter%]/parent::*';
$xpath = str_replace('%filter%', $filter, $xpath);

$currencies = $xchange->xpath($xpath);

Happy looping!

风情万种。 2024-11-12 11:47:55

只需替换

foreach($xchange as $curr) // loop through our books
{
        echo "
        <tr>
                <td>{$curr->NAME}</td>
                <td>{$curr->CURRENCYCODE}</td>
                <td>{$curr->COUNTRY}</td>
                <td>{$curr->RATE}</td>
        </tr>";
}

foreach($xchange as $curr) // loop through our books
{
    if (in_array($curr->CURRENCYCODE, array('usd', 'gbp', 'cad'))) {
            echo "
            <tr>
                    <td>{$curr->NAME}</td>
                    <td>{$curr->CURRENCYCODE}</td>
                    <td>{$curr->COUNTRY}</td>
                    <td>{$curr->RATE}</td>
            </tr>";
    }
}

Simply replace

foreach($xchange as $curr) // loop through our books
{
        echo "
        <tr>
                <td>{$curr->NAME}</td>
                <td>{$curr->CURRENCYCODE}</td>
                <td>{$curr->COUNTRY}</td>
                <td>{$curr->RATE}</td>
        </tr>";
}

with

foreach($xchange as $curr) // loop through our books
{
    if (in_array($curr->CURRENCYCODE, array('usd', 'gbp', 'cad'))) {
            echo "
            <tr>
                    <td>{$curr->NAME}</td>
                    <td>{$curr->CURRENCYCODE}</td>
                    <td>{$curr->COUNTRY}</td>
                    <td>{$curr->RATE}</td>
            </tr>";
    }
}
请止步禁区 2024-11-12 11:47:55

我这样做如下

function xml ($url) {
  $text = file_get_contents($url) or die("ERROR: Unable to read file");

  $p = xml_parser_create();

  xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
  xml_parse_into_struct($p, $text, $vals, $index);
  xml_parser_free($p);

  for($i=0; $i<count ($index['Title']); $i++) {
    foreach(array('var1', 'var2', 'var3') as $key) {
      $info[$i][$key] = $vals[$index[$key][$i]]['value'];
    }
  }
}

I do this as follows

function xml ($url) {
  $text = file_get_contents($url) or die("ERROR: Unable to read file");

  $p = xml_parser_create();

  xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 0);
  xml_parse_into_struct($p, $text, $vals, $index);
  xml_parser_free($p);

  for($i=0; $i<count ($index['Title']); $i++) {
    foreach(array('var1', 'var2', 'var3') as $key) {
      $info[$i][$key] = $vals[$index[$key][$i]]['value'];
    }
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文