XmlParser.php 2.32 KB
<?php
/**
 * Created by PhpStorm.
 * User: Cibermag
 * Date: 10.09.2015
 * Time: 17:47
 */

namespace yii\multiparser;


class XmlParser implements ParserInterface{
    /** @var экземляр SplFileObject читаемого файла */
    public $file;
    public $node;

    public function read()
    {
        $file = $this->file;
        $result = self::xml2array( $file->getPathname() );
        if ( isset($this->node) ) {
            $result = $result[$this->node];
        }

        //\common\components\CustomVarDamp::dumpAndDie($result);
        $result = DynamicFormHelper::CreateAssocArray($result, \Yii::$app->multiparser->getConfiguration('xml','basic_column'));
        \common\components\CustomVarDamp::dumpAndDie($result);
    }

    public function setup()
    {


    }


    /**
     * Converts an XML string to a PHP array
     *
     * @uses recursiveXMLToArray()
     * @param string $file_path
     * @return array
     */
    protected static function xml2array( $file_path ) {

        try {
            $xml = new \SimpleXMLElement( $file_path, 0, true );
            //\common\components\CustomVarDamp::dumpAndDie($xml->children()->children());
            $result = self::recursiveXMLToArray( $xml );
        } catch(Exception $ex) {

            throw $ex;
        }

        return $result;
    }

    /**
     * Convert a XML string to a PHP array recursively. Do not
     * call this function directly, Please use {@link Convert::xml2array()}
     *
     * @param SimpleXMLElement
     *
     * @return mixed
     */
    protected static function recursiveXMLToArray($xml) {
        if(is_object($xml) && get_class($xml) == 'SimpleXMLElement') {
            $attributes = $xml->attributes();
            foreach($attributes as $k => $v) {
                if($v) $a[$k] = (string) $v;
            }
            $x = $xml;
            $xml = get_object_vars($xml);
        }

        //\common\components\CustomVarDamp::dump($xml);
        if(is_array($xml)) {
            if(count($xml) == 0) return (string) $x; // for CDATA
            foreach($xml as $key => $value) {
                $r[$key] = self::recursiveXMLToArray($value);
            }
            if(isset($a)) $r['@'] = $a; // Attributes
            return $r;
        }
        //\common\components\CustomVarDamp::dumpAndDie($xml);
        return (string) $xml;
    }
}