Site icon Hip-Hop Website Design and Development

No data saved to database (from PHP based API call)

I got the following code in my functions.php

add_action('wp_ajax_nopriv_get_cars_from_api', 'get_cars_from_api');
add_action('wp_ajax_get_cars_from_api', 'get_cars_from_api');
function get_cars_from_api() { 
    $url = "https://gw.bilinfo.net/listingapi/api/export";

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    $headers = array(
       "Authorization: Basic ZGVtbzogb2NmQjZYekY3Mw",
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    //for debug
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    $resp = curl_exec($curl);
    curl_close($curl);
    $arr = json_decode($resp, true);

    wp_remote_post(admin_url('admin-ajax.php?action=hent_biler_fra_bilinfo'), [
        'blocking' => true,
        'sslverify' => false,
    ]);

foreach($arr['Vehicles'] as $car) {
        $car_slug = sanitize_title($car['Mileage']);
        $inserted_car = wp_insert_post([
            'post_name' => $car_slug,
            'post_title' => $car_slug,
            'post_type' => 'cars',
            'post_status' => 'publish'
        ]);

        if(is_wp_error($inserted_car)) {
            continue;
        }
        print_r($car['Mileage'] . '/n/n');
        $fillable = [
            'field_61f2c91e13181' => $car['Mileage']
        ];

        foreach($fillable as $key => $name) {
            update_field($name, $car->$name, $inserted_car);
        };

    }

}

I have a issue with the following part.

$fillable = [
        'field_61f2c91e13181' => $car['Mileage']
    ];

    foreach($fillable as $key => $name) {
        update_field($name, $car->$name, $inserted_car);
    };

The issue is most likely that I navigate my JSON response as $car['Mileage'] and not $car->mileage, so when I use $car->$name it won’t work. What’s my alternative?

Alternatively it can be that I lost ideas of how to grab just Mileage. It seems like the $car[‘Mileage’] prints fine in my print_r, but it doesnt save anything on my object.

I use Advanced Custom Fields (where field_61f2c91e13181 and update_field comes from)

Where did I misunderstand something, can anyone help me out?

Thanks in advance.

UPDATE!
I managed to save objects, but not data

I use a paid API but for demo please see https://developer.bilinfo.net/content/Bilinfo_XML_API.pdf