laravel - laravel simplexml 加载文件数据库凝乳
问题描述
我想将“simplexml_load_file”附带的一些数据保存到数据库中,但是没有保存,不知道问题出在哪里?
我想保存什么“美元、欧元、英镑”
"message": "Object of class Illuminate\\Support\\Facades\\Date could not be converted to string",
Route::post('/exchange_rates',[ToolsController::class, 'kurlar']);
Schema::create('exchanges', function (Blueprint $table) {
$table->id();
$table->boolean('buying_rate');
$table->boolean('selling_rate');
$table->date('date');
$table->string('currency');
$table->timestamps();
})
public function kurlar()
{
$products = simplexml_load_file('https://www.tcmb.gov.tr/kurlar/today.xml');
$pred = [0, 3, 4];
print_r($products);
foreach ($products as $product) {
$exchange = new Exchange;
$exchange->buying_rate = $product->ForexBuying;
$exchange->selling_rate = $product->ForexSelling;
$exchange->date = new Date();$product->attributes['Date'];
$exchange->currency = $product->attributes['CurrencyCode'];
$exchange->save();
}
}
解决方案
首先,错误:Object of class Illuminate\\Support\\Facades\\Date could not be converted to string
意味着您无法通过在模型中传递new Date()
对象来保存日期属性,因为简单的 Laravel 允许您将日期作为字符串传递给所需的属性。
在实施和修改您的代码后,我从中获得了这个工作版本:
public function kurlar(){
$products = simplexml_load_file('https://www.tcmb.gov.tr/kurlar/today.xml');
$exchanges = [];
foreach ($products as $product) {
$exchange = new Exchange;
$exchange->buying_rate = get_object_vars($product->ForexBuying)[0];
$exchange->selling_rate = get_object_vars($product->ForexSelling)[0] ?? 0; //0 as default value when returning null from ForexSelling
// '2021-09-19' as a default date because all the products returns null on data
$exchange->date = '2021-09-19';
$exchange->currency = get_object_vars($product->attributes()['CurrencyCode'])[0];
if(in_array($exchange->currency, ['USD', 'EUR', 'GBP'])){
$exchange->save();
array_push($exchanges, $exchange);
}
}
return $exchanges;
}
或者,您可以使用for
循环检查索引:
for ($i=0; $i < count($products->Currency) ; $i++) {
$product = $products->Currency[$i];
# code...
$exchange = new Exchange;
$exchange->buying_rate = get_object_vars($product->ForexBuying)[0];
$exchange->selling_rate = get_object_vars($product->ForexSelling)[0] ?? 0; //0 as default value when returning null from ForexSelling
// '2021-09-19' as a default date because all the products returns null on data
$exchange->date = '2021-09-19';
$exchange->currency = get_object_vars($product->attributes()['CurrencyCode'])[0];
if(in_array($i, [0, 3, 4])){
$exchange->save();
array_push($exchanges, $exchange);
}
}
推荐阅读
- postgresql - 在 dockerized flask + postgres 应用程序中管理 pytest 测试的任何推荐方法?
- javascript - 在 iframe 中结合 2 个 onload 命令
- php - 将数组与公共键组合以进行 MYSQL 更新
- hash - 区块链散列中如何计算印章号?
- google-oauth - 登录服务器端应用程序并弃用
- php - Magento 2.2.2 错误:配置文件已更改。运行 app:config:import 或 setup:upgrade 命令同步配置
- laravel - 我的 Laravel 容器中的路由没有更新
- android - 构建一个 android 客户端应用程序以与支持 HTTP2 的流服务交互
- c - 无法将较小的数组复制到 C 中较大的预填充数组中
- robocopy - Robocopy - 错误 124 (0x0000007C) 创建目标目录