dkrnl / SimpleXMLReader

Wrapped XMLReader class, for simple SAX-reading of huge xml.
112 stars 43 forks source link

функция в конце обработки элемента xml #3

Closed blaqdog closed 9 years ago

blaqdog commented 9 years ago

вот таким образом обрабатываю xml

class ExampleXmlReader1 extends SimpleXMLReader
{

    public function __construct()
    {

        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer"), array($this, "callbackOffer"));

        // ТИП СДЕЛКИ
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/type"), array($this, "callbackType"));
        // ВИД НЕДВИЖИМОСТИ
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/category"), array($this, "callbackCategory"));
        // АДРЕС
        //$this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/location/country"), array($this, "callbackREALTY_REGION"));
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/location/region"), array($this, "callbackREALTY_REGION"));//область 92
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/location/locality-name"), array($this, "callbackREALTY_LOCATION"));//город 94
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/location/address"), array($this, "callbackREALTY_STREET"));//улица+дом 95+96

        //ОПИСАНИЕ
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/description"), array($this, "callbackREALTY_DESCRIPTION"));
        //КАРТИНКИ
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/image"), array($this, "callbackIMAGES"));
        //ПЛОЩАДЬ
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/area/value"), array($this, "callbackREALTY_AREA"));
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/living-space/value"), array($this, "callbackREALTY_AREA_LIVE"));
        //ПАРАМЕТРЫ
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/rooms"), array($this, "callbackREALTY_ROOMS"));
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/floor"), array($this, "callbackREALTY_FLOOR"));
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/floors-total"), array($this, "callbackREALTY_OF_FLOORS"));
         //СТОИМОСТЬ
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/price/value"), array($this, "callbackREALTY_PRICE"));
        //площадь кухни
        $this->registerCallback(@iconv('Windows-1251//TRANSLIT//IGNORE','UTF-8', "/realty-feed/offer/kitchen-space/value"), array($this, "callbackREALTY_AREA_KITCHEN"));

    }

    //OFFER
    protected function callbackOffer($reader)
    {
        global $adsArray;
        global $offerArray;
        global $adsPropDescription;

        $adsArray = array();
        $adsPropDescription = array();
        $offerArray = array();

        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
        $ref = (string) $attributes->{"internal-id"};
        if ($ref) {
            $internalID = floatval((string) $xml);
            $xpath = $this->currentXpath();

            //$adsArray[] = "offer";

            $adsArray[] = "$ref";
            $offerArray[] = "offer";

            $adsPropDescription[] = "151";
        }
        return true;
    }
    //ТИП СДЕЛКИ
    protected function callbackType($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "type";
            $xpath = $this->currentXpath();
        //echo "</br>".$value;
           // echo "1 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value;\n");
            $adsArray[] = @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $offerArray[] = "";
            $adsPropDescription[] = "51";
        return true;
    }
    //ВИД НЕДВИЖИМОСТИ
    protected function callbackCategory($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "category";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "2 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            $adsArray[] = @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsPropDescription[] = "56";
            $offerArray[] = "";

        return true;
    }
    //REALTY_REGION
    protected function callbackREALTY_REGION($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_REGION";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "3 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            $adsArray[] = @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsPropDescription[] = "92";
            $offerArray[] = "";

        return true;
    }
    //REALTY_LOCATION
    protected function callbackREALTY_LOCATION($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_LOCATION";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "4 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            $adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsPropDescription[] = "94";
            $offerArray[] = "";

        return true;
    }
    //REALTY_STREET
    protected function callbackREALTY_STREET($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_STREET";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "5 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value;\n");
            $adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsPropDescription[] = "95";
            $offerArray[] = "";

        return true;
    }
    //REALTY_BUILDING
    protected function callbackREALTY_BUILDING($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_BUILDING";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "6 " .  @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            $adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsPropDescription[] = "96";
            $offerArray[] = "";

        return true;
    }
    //REALTY_AREA
    protected function callbackREALTY_AREA($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_AREA";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "7 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            $adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsPropDescription[] = "52";
            $offerArray[] = "";

        return true;
    }
    //REALTY_AREA_LIVE
    protected function callbackREALTY_AREA_LIVE($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_AREA_LIVE";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "8 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            $adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsPropDescription[] = "57";
            $offerArray[] = "";

        return true;
    }

    //REALTY_ROOMS
    protected function callbackREALTY_ROOMS($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_ROOMS";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "10 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            //$adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsArray[] = $value;
            $adsPropDescription[] = "60";
            $offerArray[] = "";

        return true;
    }
    //REALTY_FLOOR
    protected function callbackREALTY_FLOOR($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_FLOOR";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "11 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            //$adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsArray[] = $value;
            $adsPropDescription[] = "63";
            $offerArray[] = "";

        return true;
    }
    //REALTY_OF_FLOORS
    protected function callbackREALTY_OF_FLOORS($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_OF_FLOORS";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "12 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            //$adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsArray[] = $value;
            $adsPropDescription[] = "89";
            $offerArray[] = "";

        return true;
    }

    //callbackREALTY_PRICE
    protected function callbackREALTY_PRICE($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_PRICE";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo " " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            $adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsPropDescription[] = "59";
            $offerArray[] = "";

        return true;
    }
    //callbackREALTY_DESCRIPTION
    protected function callbackREALTY_DESCRIPTION($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_DESCRIPTION";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo " " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            $adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsPropDescription[] = "detail text";
            $offerArray[] = "";

            $firstXmlIteration = false;

        return true;
    }

    //IMAGES
    protected function callbackIMAGES($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "IMAGES";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "13 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            //$adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsArray[] = $value;
            $adsPropDescription[] = "85";
            $offerArray[] = "";

        return true;
    }

        //REALTY_AREA_KITCHEN
    protected function callbackREALTY_AREA_KITCHEN($reader)
    {
        global $adsArray;
global $offerArray;
global $adsPropDescription;
        $value = "";
        $xml = $reader->expandSimpleXml();
        $attributes = $xml->attributes();
            $value = (string)$xml;
            $description = "REALTY_AREA_KITCHEN";
            $xpath = $this->currentXpath();
            //echo "</br>".$value;
            //echo "9 " . @iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$description: = $value;\n");
            //$adsArray[] = iconv('UTF-8','Windows-1251//TRANSLIT//IGNORE', "$value");
            $adsArray[] = $value;
            $adsPropDescription[] = "58";
            $offerArray[] = "";
            FormRequestForObject($adsArray,$adsPropDescription);

            return true;

            //FormRequestForObject($adsArray,$adsPropDescription);

    }

}

элемент содержит в себе другие элементы со значениями, я сохраняю их в массив, и в конце каждого offer запускаю функцию FormRequestForObject() по сохранению данных с этого массива. Все работает отлично, за исключением того, что когда в xml элементы находятся ниже kitchen-space - они не сохраняются в массив. Это происходит потому, что я вызываю функцию именно на kitchen-space.

Каким образом мне вызывать функцию, чтобы все элементы сохранялись, которые есть в offer. Может быть есть какая то конструкция, которая бы вызывала функцию при закрытии тега /offer

пример загружаемого xml

<?xml version="1.0" encoding="UTF-8"?>
<realty-feed xmlns="http://webmaster.yandex.ru/schemas/feed/realty/2010-06">
    <generation-date>2015-07-21T10:10:20+03:00</generation-date>
    <offer internal-id="30898">
        <type>аренда</type>
        <property-type>жилая</property-type>
        <url>http://rdgservice.ru/view1.php?c=0&amp;t=0&amp;id=30898</url>
        <creation-date>2015-07-21T10:10:20+03:00</creation-date>
        <last-update-date>2015-07-21T10:10:20+03:00</last-update-date>
        <sales-agent>
            <name>Татьяна</name>
            <phone>+7(967)1398060</phone>
            <category>агентство</category>
            <organization>Агентство недвижимости "RDG SERVICE"</organization>
            <url>http://rdgservice.ru</url>
        </sales-agent>
        <price>
            <value>40000</value>
            <currency>RUR</currency>
            <period>месяц</period>
        </price>
        <description>Сдается 2х комнатная кв. в Новой Трехгорке. Комнаты 16 и 14 кв.м. Кухня 12м. большая ванная комната. Качественный ремонт. Новая мебель. Встроенная техника (посудомоечная и стиральная машина). WiFi интернет и цифровое ТВ. Окна выходят на Подушкинский лесопарк. Подъезд чистый, консьержка. Рядом автобусная остановка и ж.д. станция. Лот № 30898</description>
        <area>
            <value>68</value>
            <unit>кв.м</unit>
        </area>
        <room-space>
            <value>16</value>
            <unit>кв.м</unit>
        </room-space>
        <room-space>
            <value>14</value>
            <unit>кв.м</unit>
        </room-space>
        <location>
            <country>Россия</country>
            <region>Московская обл.</region>
            <direction>Минское шоссе</direction>
            <distance>6</distance>
            <locality-name>Одинцово</locality-name>
            <address>Кутузовская,33</address>
        </location>
        <category>квартира</category>
        <rooms>2</rooms>
        <rooms-offered>2</rooms-offered>
        <room-furniture>1</room-furniture>
        <kitchen-furniture>1</kitchen-furniture>
        <television>1</television>
        <washing-machine>1</washing-machine>
        <refrigerator>1</refrigerator>
        <balcony>балкон</balcony>
        <floor>8</floor>
        <floors-total>19</floors-total>
        <living-space>
            <value>30</value>
            <unit>кв.м</unit>
        </living-space>
        <kitchen-space>
            <value>12</value>
            <unit>кв.м</unit>
        </kitchen-space>
        <image>http://rdgservice.ru/bdfiles/flat/30898/55adeccab271e.jpg</image>
        <image>http://rdgservice.ru/bdfiles/flat/30898/55adeccb03662.jpg</image>
        <image>http://rdgservice.ru/bdfiles/flat/30898/55adeccb48017.jpg</image>
        <image>http://rdgservice.ru/bdfiles/flat/30898/55adeccb8aadd.jpg</image>
        <image>http://rdgservice.ru/bdfiles/flat/30898/55adeccbcc1c8.jpg</image>
        <image>http://rdgservice.ru/bdfiles/flat/30898/55adeccc1d4e3.jpg</image>
        <building-type>Панельный</building-type>
        <heating-supply>1</heating-supply>
        <water-supply>1</water-supply>
        <sewerage-supply>1</sewerage-supply>
        <electricity-supply>1</electricity-supply>
        <gas-supply>1</gas-supply>
        <phone>1</phone>
    </offer>
</realty-feed>

если kitchen-space опустить вниз, работает отлично, а хотелось бы, чтобы функция сохраняла все элементы при любом их расположении (функция запускалась на закрытии тега offer, или другим способом, но в конце элемента offer)

dkrnl commented 9 years ago

Код избыточен, необходимо обработку сделать в одном узле "/realty-feed/offer", другие обработчики, например "/realty-feed/offer/type" -- бессмыслены.

protected function callbackOffer($reader)
{
    $offer = $reader->expandSimpleXml(); // тут уже весь узел <offer>...</offer>
    $attributes = $offer->attributes();
    echo "ID: ", strval($attributes ->{"internal-id"}), "\n";
    echo "Тип: ", strval($offer->{"type"}), "\n";
}