php 使用php从另一个网站获取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7144844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 02:08:31  来源:igfitidea点击:

Fetching data from another website with php

php

提问by Rafael Sedrakyan

I need to fetch data from this web page central bank of armenia

我需要从这个网页中获取数据亚美尼亚中央银行

In my html form user must insert the price of his supply. He/she selects the currency (USD, EUR or AMD) and types its value. After that I need to convert inserted price to other two currencies and add them to my database. So how can I get USD and EUR exchange rates from the site given above using PHP and attach them to variables.

在我的 html 表单中,用户必须插入他的供应价格。他/她选择货币(美元、欧元或 AMD)并输入其价值。之后,我需要将插入的价格转换为其他两种货币并将它们添加到我的数据库中。那么如何使用 PHP 从上面给出的站点获取美元和欧元汇率并将它们附加到变量。

回答by Matej Balanti?

I normally don't do end-solutions in Q&A forums, but let it be, you challenged me :)

我通常不会在问答论坛中做最终解决方案,但不管怎样,你挑战了我:)

$content = file_get_contents("http://www.cba.am/am/SitePages/Default.aspx");

preg_match('#<b>USD</b>(.*)<em class="w_50">([0-9\.]*)</em><em class="w_50">([0-9\.]*)</em>#Uis', $content, $USDmatch);
preg_match('#<b>EUR</b>(.*)<em class="w_50">([0-9\.]*)</em><em class="w_50">([0-9\.]*)</em>#Uis', $content, $EURmatch);
preg_match('#<b>GBP</b>(.*)<em class="w_50">([0-9\.]*)</em><em class="w_50">([0-9\.]*)</em>#Uis', $content, $GBPmatch);

$eur = $EURmatch[3];
$usd = $USDmatch[3];
$gbp = $GBPmatch[3];

echo "EUR: $eur USD: $usd GBP: $gbp";

Let me, however, remind you that this kind of data fetching may be considered copyright infringement and abuse of Central bank of Armenia's servers.

但是,让我提醒您,这种数据获取可能会被视为侵犯亚美尼亚中央银行服务器的版权和滥用。

Also, this is not a permanent solution, since bank may change it's website HTML structure anytime, breaking your code.

此外,这不是一个永久性的解决方案,因为银行可能会随时更改其网站 HTML 结构,从而破坏您的代码。

I would suggest using some kind of public API for that.

我建议为此使用某种公共 API。

回答by Dave Lasley

I would recommend using cURL to actually make the call then DOM to parse. The advantage to using DOM is allowing you a little bit of leeway when it comes to changes on the website. The advantage to curl being extended flexibility and the ability to return errors. This will require quite a bit of studying on your part in order to determine the correct values to look for. The below code should get you started:

我建议使用 cURL 来实际进行调用,然后使用 DOM 进行解析。使用 DOM 的优点是在网站更改时允许您有一点回旋余地。curl 的优点是扩展了灵活性和返回错误的能力。这将需要您进行大量研究,以确定要查找的正确值。下面的代码应该让你开始:

// Curl
function curl($url, $post=''){


        //cURL options
        $options = array(

            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => false,    // don't return headers
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 500,      // timeout on connect
            CURLOPT_TIMEOUT        => 500,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_USERAGENT      => "",
            CURLOPT_COOKIESESSION  => false,
            CURLOPT_COOKIEJAR     => $this->ckfile, // Cookies
            CURLOPT_COOKIEFILE     => $this->ckfile, //Cookies...yum


        );

        //Go go go!
        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );

        $output['content'] = curl_exec( $ch );
        $output['err']     = curl_errno( $ch );
        $output['errmsg']  = curl_error( $ch );
        $output['header']  = curl_getinfo( $ch );
        return $output;

    }

Once you have $output, you can parse with DOM. Few ways you can go about it, I recommend XPATH queries

一旦你有了 $output,你就可以用 DOM 解析了。有几种方法可以解决,我推荐 XPATH 查询

//Create DOM
        $doc = new DOMDocument;
        @$doc->loadHTML($curl['content']);
        $doc->preserveWhiteSpace = false;

$xpath = new DOMXpath($doc);

        $nodeList = $xpath->query("//div[@id='test']"); // I would recommend trying to find an element that contains the currency elements, but has an attribute that will most likely not be changed. IDs work well, sometime div classes also work. Check out http://www.exampledepot.com/egs/org.w3c.dom/xpath_GetElemByText.html

        foreach($nodeList as $node){

            // From here you would want to select the element http://php.net/manual/en/domdocument.getelementsbytagname.php

}

From there you return it. I would instead recommend parsing http://themoneyconverter.com/RSSFeeds.aspx

从那里你返回它。我会建议解析http://themoneyconverter.com/RSSFeeds.aspx

回答by Pons

There is a similar function in this classthat do exchange rates from Bank of Italy. Bank of Italy has a public link to give you exchange rates daily. Perhaps also Bank of Armenia gives a public link with exchange rates, use it (if there is) so you don't have to do too complex parsing and you don't have any copyright problems.

这个类中有一个类似的函数来处理来自意大利银行的汇率。意大利银行有一个公共链接,可以每天为您提供汇率。也许亚美尼亚银行也提供了一个与汇率的公共链接,使用它(如果有的话)这样你就不必做太复杂的解析并且你没有任何版权问题。