How to get country codes using the ODOO xmlrpc API and PHP.

To fetch country codes from an Odoo instance using PHP 8.2, you’ll need to use the Odoo XML-RPC API. Below is an example of how to achieve this:

Step 1: Set Up PHP Environment

Ensure you have PHP 8.2 installed with the necessary extensions, including the cURL extension, which is used for making HTTP requests.

Step 2: Connect to Odoo Using XML-RPC

Here’s how you can retrieve the list of countries and their codes.

Full PHP Example:

<?php
// Odoo connection details
$odooUrl = "https://your-odoo-instance.com";
$db = "your_database";
$username = "your_username";
$password = "your_password";

// XML-RPC endpoints
$commonEndpoint = "$odooUrl/xmlrpc/2/common";
$objectEndpoint = "$odooUrl/xmlrpc/2/object";

// Function to send XML-RPC requests
function xmlrpcRequest($url, $method, $params)
{
    $request = xmlrpc_encode_request($method, $params);
    $context = stream_context_create([
        'http' => [
            'method' => "POST",
            'header' => "Content-Type: text/xml",
            'content' => $request,
        ]
    ]);
    $response = file_get_contents($url, false, $context);
    return xmlrpc_decode($response);
}

// Step 1: Authenticate with the common endpoint
$uid = xmlrpcRequest($commonEndpoint, 'authenticate', [$db, $username, $password, []]);

if (!$uid) {
    die("Authentication failed!");
}

// Step 2: Fetch country data
$countries = xmlrpcRequest($objectEndpoint, 'execute_kw', [
    $db,
    $uid,
    $password,
    'res.country',
    'search_read',
    [[]], // No filters, fetch all countries
    ['fields' => ['id', 'name', 'code'], 'limit' => 1000] // Retrieve ID, Name, and Code
]);

// Step 3: Display results
foreach ($countries as $country) {
    echo "ID: {$country['id']}, Name: {$country['name']}, Code: {$country['code']}\n";
}
?>

Explanation of the Code

  1. Authentication:
    • The authenticate method is called on the common endpoint to log in and retrieve the uid (user ID).
  2. Data Retrieval:
    • The execute_kw method is called on the object endpoint to retrieve data from the res.country model.
    • The search_read method is used to both search for records and fetch their details.
    • The fields parameter specifies the fields to retrieve (id, name, and code).
  3. Display Results:
    • The data is looped through, and the id, name, and code fields of each country are printed.

Sample Output

ID: 1, Name: United States, Code: US
ID: 2, Name: Canada, Code: CA
ID: 3, Name: Mexico, Code: MX
...

Requirements

  1. Replace placeholders (your-odoo-instance.com, your_database, your_username, your_password) with your actual Odoo instance details.
  2. Ensure the Odoo instance is reachable and the credentials have sufficient permissions to access the res.country model.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *