【发布时间】:2013-05-27 20:45:36
【问题描述】:
我试图让这个脚本根据大于/小于脚本输出结果。当我运行这个脚本时,它会输出文本文件中的第一行。关于我缺少什么的任何建议?
<?php
$lines = file('unique.txt'); // Reads the file with the list of user numbers
$timestamp = time(); // Defines time for below renaming
foreach ($lines as $usernumber) { // Loops line by line
$link = 'http://backpack.tf/api/IGetUsers/v2/?&steamids=' . $usernumber . '&format=json';
$json = file_get_contents($link); // Reads link (this ^)
$data = json_decode($json); // Defines decode as json
if (!empty($data)) {
$profiles = array(); //init array so we can use $profiles[] later
foreach ($data->response->players as $player) { // Loop thrugh all the players
$player2 = $player->backpack_value;
if ($player2 < 9999999) { // Check the backpack_value
$profiles[] = $player; // Assign the required players to a new array
var_dump($profiles); // Dump the array to browser for debugning
$fh = fopen("final." . $timestamp . ".txt", 'a') or die("can't open file"); // Opens final.txt to write in
fwrite($fh, $usernumber); // Writes the parsed results to final.txt
} //closes if $playtime
} //closes foreach $data
} //closes if !empty
else {
echo $data;
}
} //closes foreach $lines
?>
Unique.txt 包含
76561197992831594
76561197992707820
76561197992146126
76561197992694522
76561197992707820
76561197992831594
JSON 示例
{
"response": {
"success": 1,
"current_time": 1369685515,
"players": {
"0": {
"steamid": "76561197992831594",
"success": 1,
"backpack_value": 47.97,
"backpack_update": 1369683750,
"name": "WesFox13",
"notifications": 0
}
}
}
}
【问题讨论】:
-
可能不是问题,但如果你移动 `$fh = fopen("final." . $timestamp . ".txt", 'a') 或 die("can' t 打开文件"); // 打开 final.txt 以写入到 foreach 之外(就像之前的行一样。现在每次找到匹配项时都重新打开文件。
-
听起来不错,我把它移到了我的个人脚本中,现在我将把它留在这个上。仍在试图找出我哪里出错了......
-
如果它只是再次回显 $data,显然 json_decode 失败。使用
json_last_error()和var_dump($json)看看发生了什么。很可能该服务器没有返回有效的 json,或者返回根本不是 json 的东西(例如,反爬虫/ToS 违规通知)。