Laravel使用simplexml_load_file读取XML存库时Date类转字符串错误如何解决
问题原因
- 日期赋值语法错误:你写的
$exchange->date = new Date();$product->attributes['Date'];中用分号截断了语句,实际给date字段赋值的是new Date()生成的Illuminate\Support\Facades\Date实例,而不是XML接口返回的日期值,Eloquent存储date类型字段时需要字符串/日期格式的内容,直接存Facade实例就触发了类型转换错误。 - 数据表字段类型错误:迁移文件里
buying_rate、selling_rate被设置为boolean布尔类型,而汇率是小数值,完全无法正确存储。 - SimpleXML取值方式错误:直接调用
$product->attributes['xxx']的写法不符合SimpleXML的使用规范,需要调用attributes()方法才能获取属性集合,且读取到的节点/属性默认都是SimpleXMLElement对象,需要手动转为字符串/数值类型才能正常存入数据库。 - 货币过滤逻辑未生效:你定义了
$pred = [0,3,4]用来筛选美元、欧元、英镑,但实际循环逻辑中没有用到这个过滤条件,会把接口返回的所有货币都存入表中,不符合你的需求。
解决方案
第一步:修正数据表迁移
修改迁移文件的汇率字段类型,删除原有错误表结构后重新执行迁移:
Schema::create('exchanges', function (Blueprint $table) { $table->id(); // 改为decimal类型,10位长度保留4位小数足够存储汇率精度 $table->decimal('buying_rate', 10, 4); $table->decimal('selling_rate', 10, 4); $table->date('date'); $table->string('currency'); $table->timestamps(); });
第二步:修正控制器业务代码
public function kurlar() { $products = simplexml_load_file('https://www.tcmb.gov.tr/kurlar/today.xml'); // 从XML根节点取统一的日期,转为Y-m-d格式适配数据库date字段 $currentDate = \Carbon\Carbon::createFromFormat('d-m-Y', (string)$products->attributes()['Date'])->toDateString(); // 定义需要存储的货币编码 $allowCurrencies = ['USD', 'EUR', 'GBP']; foreach ($products as $product) { $currencyCode = (string)$product->attributes()['CurrencyCode']; // 过滤不需要的货币 if (!in_array($currencyCode, $allowCurrencies)) { continue; } $exchange = new Exchange; // 把XML节点值转为浮点型存储 $exchange->buying_rate = (float)$product->ForexBuying; $exchange->selling_rate = (float)$product->ForexSelling; $exchange->date = $currentDate; $exchange->currency = $currencyCode; $exchange->save(); } }
内容的提问来源于stack exchange,提问作者Selaminko Elam
相关产品推荐
相关产品推荐

