如何解析该表并从中提取数据? [英] How to parse this table and extract data from it?

查看:70
本文介绍了如何解析该表并从中提取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表: http://www.nbs.rs/kursnaListaModul/srednjiKurs.faces?lang = lat

这是一个货币兑换清单,我需要从中提取一些数据.表格左侧是货币ID号.可以根据指定行的ID提取数据吗?

It is a currency exchange list and I need to extract some data from it. On left side of the table are currency ID numbers. Would it be possible to extract data from specified rows based on their IDs?

例如,从上表中,我要提取ID为978、203和348的货币.

For example, from the table above, I want to extract currencies with IDs 978, 203, and 348.

输出应为:

  • 104,2182欧元
  • 4,2747捷克克朗
  • 38,7919福林

通过在此处查看类似的示例,我想到了以下内容: http://pastebin.com/hFZs1H7C

By looking at similar examples here, I came up with this: http://pastebin.com/hFZs1H7C

我需要某种方式来检测ID和正确的打印值...在编程方面,我是菜鸟,我需要您的帮助.

I need somehow to detect IDs and the print proper values... I'm noob when it comes to programming and I need your help.

<?php
$data = file_get_contents('http://www.nbs.rs/kursnaListaModul/srednjiKurs.faces?lang=lat');

$dom = new domDocument;

@$dom->loadHTML($data);
$dom->preserveWhiteSpace = false;
$tables = $dom->getElementsByTagName('table');

$rows = $tables->item(1)->getElementsByTagName('tr');

foreach ($rows as $row) {
        $cols = $row->getElementsByTagName('td');
                foreach ($cols as $col) {

                                echo $col;

                }
}

?>

推荐答案

将表数据收集为数组以供以后使用:

Collecting the table data as array for later usage:

$dom = new DomDocument;
$dom->loadHtmlFile('http://www.nbs.rs/kursnaListaModul/srednjiKurs.faces?lang=lat');

$xpath = new DomXPath($dom);

// collect header names
$headerNames = array();
foreach ($xpath->query('//table[@id="index:srednjiKursLista"]//th') as $node) {
    $headerNames[] = $node->nodeValue;
}

// collect data
$data = array();
foreach ($xpath->query('//tbody[@id="index:srednjiKursLista:tbody_element"]/tr') as $node) {
    $rowData = array();
    foreach ($xpath->query('td', $node) as $cell) {
        $rowData[] = $cell->nodeValue;
    }

    $data[] = array_combine($headerNames, $rowData);
}

print_r($data);

输出:

Array
(
    [0] => Array
        (
            [ŠIFRA VALUTE] => 978
            [NAZIV ZEMLJE] => EMU
            [OZNAKA VALUTE] => EUR
            [VAŽI ZA] => 1
            [SREDNJI KURS] => 104,2182
        )

    ...
)

示例用法:

foreach ($data as $entry) {
    printf(
        '%s %s' . PHP_EOL,
        $entry['OZNAKA VALUTE'],
        $entry['SREDNJI KURS']
    );
}

这篇关于如何解析该表并从中提取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆