Home / eCommerce / Product Detail from External Source
Duplicate Snippet

Embed Snippet on Your Site

Product Detail from External Source

Code Preview
php
<?php
function my_produkt_detail($ean, $field_path = '', $default = '') {
    static $cache = array();
    try {
        if (empty($ean) || !is_string($ean)) {
            return $default;
        }
        if (!isset($cache[$ean])) {
            $detail_url = "https://db.ecoinform.de/ecodb.php/produktdetail?partner=2a3ea8f338618ff8&lang=DE&ean=" . urlencode($ean);
            $response = wp_remote_get($detail_url, array(
                'timeout' => 30,
                'headers' => array(
                    'User-Agent' => 'WordPress/' . get_bloginfo('version') . '; ' . home_url()
                )
            ));
            if (is_wp_error($response)) {
                $cache[$ean] = null;
                return $default;
            }
            $status_code = wp_remote_retrieve_response_code($response);
            if ($status_code !== 200) {
                $cache[$ean] = null;
                return $default;
            }
            $xml_body = wp_remote_retrieve_body($response);
            if (empty($xml_body)) {
                $cache[$ean] = null;
                return $default;
            }
            libxml_use_internal_errors(true);
            libxml_clear_errors();
            $detail_xml = simplexml_load_string($xml_body, 'SimpleXMLElement', LIBXML_NOCDATA);
            if ($detail_xml === false) {
                $cache[$ean] = null;
                libxml_use_internal_errors(false);
                return $default;
            }
            $cache[$ean] = $detail_xml;
            libxml_use_internal_errors(false);
        }
        $data = $cache[$ean];
        if ($data === null) {
            return $default;
        }
        if (empty($field_path)) {
            return $data;
        }
        $keys = explode('.', $field_path);
        $current = $data;
        foreach ($keys as $key) {
            if (isset($current->$key)) {
                $current = $current->$key;
            } else {
                return $default;
            }
        }
        return (string) $current;
    } catch (Exception $e) {
        error_log('Product Detail Function - Error for EAN ' . $ean . ': ' . $e->getMessage());
        return $default;
    }
}

Comments

Add a Comment