首页 > 解决方案 > 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();
        }
    }

标签: laravel

解决方案


首先,错误: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);
    }
}

推荐阅读