Парсер фида Google Merchant Center

cepera007

Разрушитель (V)
Сообщения
95
Симпатии
75
Баллы
1 350
Есть стандартный фид Мерчанта
XML:
<item>
    <g:id>1618827937</g:id>
    <g:title>Сверлильный электромагнитный станок TITAN PMD16</g:title>
    <g:description>Напряжение: 220 В. Мощность: 1500 Вт. Диаметр сверления: 16 мм. Обороты: 350 об/мин. Электромагнитная сила: 11500Н. Максимальный ход шпинделя: 140 мм. Гарантия: 12 месяцев.</g:description>
    <g:link>https://domain.com/product1.html</g:link>
    <g:image_link>https://domain.com/stanok.jpg</g:image_link>
    <g:additional_image_link>https://domain.com/stanok1.jpg</g:additional_image_link>
   <g:additional_image_link>https://domain.com/stanok2.jpg</g:additional_image_link>
    <g:availability>in stock</g:availability>
    <g:price>8742.00 UAH</g:price>
    <g:product_type>промышленное оборудование и станки &gt; станки &gt; металлообрабатывающие станки &gt; сверлильные станки</g:product_type>
    <g:brand>Титан</g:brand>
    <g:product_detail>
        <g:attribute_name>Сила магнита (макс.) кН</g:attribute_name>
        <g:attribute_value>11.5</g:attribute_value>
    </g:product_detail>
    <g:product_detail>
        <g:attribute_name>Предельный диаметр сверления, мм</g:attribute_name>
        <g:attribute_value>16</g:attribute_value>
    </g:product_detail>
    <g:product_detail>
        <g:attribute_name>Ход шпинделя. мм</g:attribute_name>
        <g:attribute_value>140</g:attribute_value>
    </g:product_detail>
</item>
Нашел такой парсер с классом XMLReader, который удобно подготавливает данные для последующего добавления в базу данных
PHP:
$xmlReader = new XMLReader();
$xmlReader->open('https://domain.com/google_merchant_center.xml');
$doc = new DOMDocument('1.0','UTF-8');
while ($xmlReader->read()) {
    if ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->localName == "item") {
        // Load the XML under the <item> tag into SimpleXML
        $data = simplexml_import_dom($doc->importNode($xmlReader->expand(), true));
        $item = [];
        // Loop over the child elements from the 'g' namespace
        foreach  ($data->children("g", true) as $tag => $value )    {
            $tag = "g:".$tag;
            // If an item with that tag name already exists, convert it to an array of items
            if ( isset($item[$tag]) )   {
                if ( !is_array($item[$tag]))    {
                    $item[$tag] = [$item[$tag]];
                }
                $item[$tag][] = (string)$value;
            }
            else    {
                // For normal items, add in the value (as a string) to the array
                $item[$tag] = (string) $value;
            }
        }
        // Store new item
        $items[] = $item;
    }
}
print_r($items);
На выходе такой массив
PHP:
Array
(
    [0] => Array
        (
            [g:id] => 1618827937
            [g:title] => Сверлильный электромагнитный станок TITAN PMD16
            [g:description] => Напряжение: 220 В. Мощность: 1500 Вт. Диаметр сверления: 16 мм. Обороты: 350 об/мин. Электромагнитная сила: 11500Н. Максимальный ход шпинделя: 140 мм. Гарантия: 12 месяцев.
            [g:link] => https://domain.com/product1.html
            [g:image_link] => https://domain.com/stanok.jpg
            [g:additional_image_link] => Array
                (
                    [0] => https://domain.com/stanok1.jpg
                    [1] => https://domain.com/stanok2.jpg
                )
            [g:availability] => in stock
            [g:price] => 8742.00 UAH
            [g:product_type] => промышленное оборудование и станки > станки > металлообрабатывающие станки > сверлильные станки
            [g:brand] => Титан
            [g:product_detail] => Array
                (
                    [0] =>
                    [1] =>
                    [2] =>
                )

        )
)
Но никак не могу разобраться, как получить данные в "product_detail".
Помогите?
 
Последнее редактирование:
Делаете новый foreach:
PHP:
$har[] ="";

foreach  ($data->children:g->product_detail as $p _detail )

{
$har = "Характеристики|".$p _detail['g:attribute_name']."|".$p _detail['g:attribute_value'];
}

Обнуление в виде $har[] =""; обязательно, так как будет расти как снежный ком со всех товаров
 
PHP:
<?php

$xmlReader = new XMLReader();
$xmlReader->open('https://domain.com/google_merchant_center.xml');
$doc = new DOMDocument('1.0','UTF-8');
while ($xmlReader->read()) {
    if ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->localName == "item") {
        // Load the XML under the <item> tag into SimpleXML
        $data = simplexml_import_dom($doc->importNode($xmlReader->expand(), true));
        $item = [];
        // Loop over the child elements from the 'g' namespace
        foreach  ($data->children("g", true) as $tag => $value )    {
            $tag = "g:".$tag;
            // If an item with that tag name already exists, convert it to an array of items
            if ( isset($item[$tag]) )   {
                if ( !is_array($item[$tag]))    {
                    $item[$tag] = [$item[$tag]];
                }
                $item[$tag][] = (string)$value;
             
                /*Начало,*/
                $har[] ="";

foreach  ($data->children:g->product_detail as $p _detail )

{
$har = "Характеристики|".$p _detail['g:attribute_name']."|".$p _detail['g:attribute_value'];
}

                $item[$tag][] = implode("\r\n",$har);
             
                /* конец*/
             
             
            }
            else    {
                // For normal items, add in the value (as a string) to the array
                $item[$tag] = (string) $value;
            }
        }
        // Store new item
        $items[] = $item;
    }
}
print_r($items);



?>
ПС.На работоспособность проверял, как концепция/
Для тестирования, скиньте фид. Можно в личку
 
Последнее редактирование:
Ругается на двоеточие - Parse error: syntax error, unexpected ':'
в $data->children:g->product_detail
 
Назад
Верх