在php文档上,我做了这个函数。
function getPrices($url) {
global $priceList; // declare global . point of this.
$src = file_get_contents_curl($url);
$dom = new DOMDocument();
$selector = new DOMXPath($dom);
$results = $selector->query('//table/tr/td/span');
foreach($results as $node) {
array_push($priceList, $node->nodeValue);
}
}
在页面底部,我给它起了几个名字。
$priceList = array();
getPrices("http://finance.naver.com/item/sise_day.nhn?code=005930");
getPrices("http://finance.naver.com/item/sise_day.nhn?code=005930&page=2");
getPrices("http://finance.naver.com/item/sise_day.nhn?code=005930&page=3");
并显示它。
echo $priceList[1];
echo $priceList[2];
echo $priceList[3];
问题是我正在使用 Joomla、Wordpress 等 CMS 类型,它们不支持使用全局变量,所以我不知道如何在不使用全局变量的情况下实现此目的。我怎样才能做到呢?我需要很多页来报废,所以我很害怕。如果我只废弃一页,
函数返回, 和
$priceList = getPrices("http://finance.naver.com/item/sise_day.nhn?code=$code");
但我不知道有多少报废案例。请帮助我...
最佳答案
一般来说,无论如何您都不应该使用全局变量。这是不好的做法。这是重组它的一种方法:
function getPrices($url) {
// this is just a local scoped temp var
$priceList = array();
$src = file_get_contents_curl($url);
$dom = new DOMDocument();
$selector = new DOMXPath($dom);
$results = $selector->query('//table/tr/td/span');
foreach($results as $node) {
array_push($priceList, $node->nodeValue);
}
// return the price list
return $priceList;
}
// here is your real price list
$priceList = array();
// array of urls
$urls = array(
"http://finance.naver.com/item/sise_day.nhn?code=005930",
"http://finance.naver.com/item/sise_day.nhn?code=005930&page=2",
"http://finance.naver.com/item/sise_day.nhn?code=005930&page=3"
// etc..
);
// loop through the urls and assign the results to the price list
foreach ($urls as $url) {
$priceList[] = getPrices($url);
}
现在你有了 $priceList
作为一个数组来执行任何操作。或者,如果您希望立即输出..您可以跳过将其放入 $priceList
并在上面的循环中进行输出
关于php - 如何在该页面中不使用全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31407436/