Advertisement
Gevz

Parser of huge XML file to woocommerce products (raw)

Oct 17th, 2018
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 11.01 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: gevz
  5.  * Date: 14.09.18
  6.  * Time: 17:47
  7.  */
  8.  
  9. namespace gt_;
  10.  
  11.  
  12. use MongoDB\BSON\ObjectId;
  13.  
  14. class gtools_core
  15. {
  16.     public function get_entry_file_list(){
  17.         $path = UPLOADDIR.'/wpallimport/files';
  18.  
  19.         $files = scandir($path);
  20.  
  21.         if($files){
  22.             $out = '<ul class="gt-filelist-ul">';
  23.             foreach ($files as $file) {
  24.                 $type = mime_content_type($path.'/'.basename($file));
  25.                 if($file == '.' || $file == '..' || $type != 'application/xml') continue;
  26.                 $out .= '<li class="gt-files" data-param="'.$file.'">'.$file.'</li>';
  27.             }
  28.             $out .= '</ul>';
  29.             return $out;
  30.         } else {
  31.             return 'ERROR!';
  32.         }
  33.     }
  34.  
  35.     public function get_file_params($filename){
  36.         $file = UPLOADDIR.'/wpallimport/files/'.basename($filename);
  37.  
  38.         $xml = simplexml_load_file($file) or die ('Cannot create object!');
  39.  
  40.         return $xml;
  41.     }
  42.  
  43.     public function read_file_by_string($filename){
  44.         $file = UPLOADDIR.'/wpallimport/files/'.basename($filename);
  45.         $i = 0;
  46.  
  47.         $descriptor = fopen($file, 'r');
  48.  
  49.         if($descriptor) {
  50.             while(($string = fgets($descriptor)) !== false || $i <= 30) {
  51.                 echo $i.' '.$string.'<br>';
  52.                 $i++;
  53.             }
  54.             fclose($descriptor);
  55.         } else {
  56.             echo 'Cannot open file.';
  57.         }
  58.     }
  59.  
  60.     public function xml_r($filename, $create_cat = 'false'){
  61.         global $product, $wpdb;
  62.         $i = 1;
  63.         $p = 0;
  64.         $file = UPLOADDIR.'/wpallimport/files/'.basename($filename);
  65.         $xml_reader = new \XMLReader();
  66.         $xml_reader->open($file);
  67.         $dom = new \DOMDocument();
  68.         $out = '';
  69.  
  70.         if($create_cat === 'true') {
  71.             $out .= '<div class="gt-cats-list"><ul>';
  72.  
  73.             $cats = $this->gt_create_cats( $file );
  74.  
  75.             foreach ( $cats as $cat ) {
  76.  
  77.                 $slug = $this->gt_transliterate( $cat["id"] . '-' . $cat, 'to_lat' );
  78.  
  79.                 $check_cat = get_term_by( 'slug', $slug, 'product_cat' );
  80.  
  81.                 if ( !$check_cat ) {
  82.                     $create_cat = wp_insert_term(
  83.                         $cat,
  84.                         'product_cat',
  85.                         array(
  86.                             'description' => '',
  87.                             'slug'        => $slug
  88.                         ) );
  89.  
  90.                     if ( $create_cat ) {
  91.                         $out .= '<li>' . $cat . ' created!</li>';
  92.                     }
  93.                 } else {
  94.                     $out .= '<li>' . $cat . ' already exist.</li>';
  95.                 }
  96.             }
  97.  
  98.             $out .= '</ul></div>';
  99.         }
  100.  
  101.         echo $out;
  102.  
  103.         echo '<ul class="gt-products-list">';
  104.  
  105.         while ($xml_reader->read() && $xml_reader->name !== 'offer');
  106.  
  107.         while ($xml_reader->name === 'offer' /* && $i <= 3 */){
  108.             $out = '';
  109.             $node       = simplexml_import_dom($dom->importNode($xml_reader->expand(), true));
  110.  
  111.             //echo var_dump($node);
  112.  
  113.             $sku            = $xml_reader->getAttribute('id');
  114.             $pname          = $node->name;
  115.             $pdesc          = $node->description;
  116.             $price          = floatval($node->price);
  117.             $category_id    = $node->categoryId;
  118.             $pictures       = $this->build_pic_array($node->picture);
  119.  
  120.             $product = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $sku));
  121.  
  122.             if(!$product) {
  123.  
  124.                 $cat = $this->gt_get_category($category_id);
  125.  
  126.                 $out .= '<li class="gt-product"><div class="gtp-num">'.$i.'</div>';
  127.                 $out .= '<div class="gtp-sku">'.$sku.'</div>';
  128.                 $out .= '<div class="gtp-title">'.$pname.'</div>';
  129.                 $out .= '<div class="gtp-cat" data-cat-id="'.$cat->term_id.'">'.$cat->name.'</div>';
  130.                 $out .= '<div class="gtp-pictures">'.$pictures.'</div>';
  131.                 $out .= '<div class="gtp-desc">'.$pdesc.'</div>';
  132.                 $out .= '<div class="gtp-price">'.$price.'</div>';
  133.                 $out .= '</li>';
  134.  
  135.  
  136.                 $add = $this->gt_import_product( $cat, $node, $sku, $price, $node->picture );
  137.  
  138.                 ob_flush();
  139.                 echo $out;
  140.  
  141.                 sleep(3);
  142.                 $i++;
  143.             } else {
  144.                 $i++;
  145.                 $p++;
  146.             }
  147.  
  148.             $xml_reader->next('offer');
  149.  
  150.         }
  151.  
  152.         echo '<li>Proccessed: '.$i.' Passed: '.$p.'. That`s all, folks!</li>';
  153.         echo '</ul>';
  154.     }
  155.  
  156.     private function build_pic_array($pic_arr){
  157.         $out = '<ul class="gtp-pic-list">';
  158.  
  159.         foreach ($pic_arr as $pic) {
  160.             $out .= '<li><img class="gtp-imgs" src="'.$pic.'"></li>';
  161.         }
  162.  
  163.         $out .= '</ul>';
  164.  
  165.         return $out;
  166.     }
  167.  
  168.     private function gt_export_product($name, $description, $price, $category_id){
  169.  
  170.     }
  171.  
  172.     private function gt_create_cats($file){
  173.         $xml_reader = new \XMLReader();
  174.         $xml_reader->open($file);
  175.         $dom = new \DOMDocument();
  176.  
  177.         while ($xml_reader->read() && $xml_reader->name !== 'categories');
  178.  
  179.         while ($xml_reader->name === 'categories') {
  180.             $node = simplexml_import_dom($dom->importNode($xml_reader->expand(), true));
  181.             return $node;
  182.         }
  183.     }
  184.  
  185.     private function gt_transliterate($string, $type = 'to_lat') {
  186.  
  187.         $cyr = [
  188.             'а','б','в','г','д','е','ё','ж','з','и','й','к','л','м','н','о','п',
  189.             'р','с','т','у','ф','х','ц','ч','ш','щ','ъ','ы','ь','э','ю','я',
  190.             'А','Б','В','Г','Д','Е','Ё','Ж','З','И','Й','К','Л','М','Н','О','П',
  191.             'Р','С','Т','У','Ф','Х','Ц','Ч','Ш','Щ','Ъ','Ы','Ь','Э','Ю','Я'
  192.         ];
  193.         $lat = [
  194.             'a','b','v','g','d','e','io','zh','z','i','y','k','l','m','n','o','p',
  195.             'r','s','t','u','f','h','ts','ch','sh','sht','a','i','y','e','yu','ya',
  196.             'A','B','V','G','D','E','Io','Zh','Z','I','Y','K','L','M','N','O','P',
  197.             'R','S','T','U','F','H','Ts','Ch','Sh','Sht','A','I','Y','e','Yu','Ya'
  198.         ];
  199.         $point_marks = ['.',',',';',':','!','?'];
  200.  
  201.         switch ($type){
  202.             case 'to_lat':
  203.                 $textcyr = $string;
  204.                 $textcyr = str_replace($cyr, $lat, $textcyr);
  205.                 $textcyr = str_replace(' ','-', $textcyr);
  206.                 $textcyr = str_replace($point_marks, '', $textcyr);
  207.                 $textcyr = strtolower($textcyr);
  208.                 return $textcyr;
  209.                 break;
  210.             case 'to_cyr':
  211.                 $textlat = $string;
  212.                 $textlat = str_replace($lat, $cyr, $textlat);
  213.                 $textlat = str_replace(' ', '-', $textlat);
  214.                 $textlat = str_replace($point_marks, '', $textlat);
  215.                 $textlat = strtolower($textlat);
  216.                 return $textlat;
  217.                 break;
  218.         }
  219.     }
  220.  
  221.     private function gt_get_category($parsed_cat_id){
  222.         $args = array(
  223.             'taxonomy'      => 'product_cat',
  224.             'orderby'       => 'name',
  225.             'hide_empty'    => 0
  226.         );
  227.  
  228.         $cats = get_categories($args);
  229.  
  230.         foreach ($cats as $cat){
  231.             $slug = $cat->slug;
  232.             $search = '"'.$parsed_cat_id.'"';
  233.             preg_match($search, $slug, $matches);
  234.  
  235.             if($matches){
  236.                 return $cat;
  237.             }
  238.         }
  239.     }
  240.  
  241.     private function gt_import_product($cat, $import, $sku, $price, $pictures){
  242.         $user = wp_get_current_user();
  243.         $user_id = $user->ID;
  244.         $wp_upload_dir = wp_upload_dir();
  245.         $images = array();
  246.  
  247.         $post = array(
  248.             'post_author'   => $user_id,
  249.             'post_content'  => $import->description,
  250.             'post_status'   => 'publish',
  251.             'post_title'    => $import->name,
  252.             'post_parent'   => '',
  253.             'post_type'     => 'product'
  254.         );
  255.  
  256.         $post_id = wp_insert_post($post, true);
  257.  
  258.         if(is_wp_error($post_id)){
  259.             return $post_id->get_error_message();
  260.         } else {
  261.  
  262.             //Images
  263.             foreach($pictures as $picture) {
  264.  
  265.                 $pic = file_get_contents($picture);
  266.                 $upload_file = wp_upload_bits(basename($picture), null, $pic);
  267.  
  268.                 $mime = wp_check_filetype(basename($picture), null);
  269.  
  270.                 $attachment = array(
  271.                     'guid'              => $wp_upload_dir['url'] . '/' . basename( $picture ),
  272.                     'post_parent'       => $post_id,
  273.                     'post_mime_type'    => $mime['type'],
  274.                     'post_title'        => basename($picture),
  275.                     'post_content'      => '',
  276.                     'post_status'       => 'inherit'
  277.                 );
  278.  
  279.                 $image_id = wp_insert_attachment($attachment, $upload_file['file'], $post_id);
  280.  
  281.                 array_push($images, $image_id);
  282.  
  283.                 // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
  284.                 require_once( ABSPATH . 'wp-admin/includes/image.php' );
  285.  
  286.                 // Generate the metadata for the attachment, and update the database record.
  287.                 $attach_data = wp_generate_attachment_metadata( $image_id, $upload_file['file'] );
  288.  
  289.                 wp_update_attachment_metadata( $image_id, $attach_data );
  290.  
  291.             }
  292.  
  293.  
  294.             // Question
  295.             if ( $post_id ) {
  296.                 //$attach_id = get_post_meta( $post_id, '_thumbnail_id', true );
  297.                 add_post_meta( $post_id, '_thumbnail_id', $images[0] );
  298.             }
  299.  
  300.             wp_set_object_terms($post_id, $cat->name, 'product_cat');
  301.             wp_set_object_terms($post_id, 'simple', 'product_type');
  302.  
  303.             // Attributes
  304.             wp_set_object_terms( $post_id, 'termo-perenos', 'pa_application', true );
  305.             wp_set_object_terms( $post_id, 'ukrayina', 'pa_country', true );
  306.             wp_set_object_terms( $post_id, 'oryginal', 'pa_originality', true );
  307.             wp_set_object_terms( $post_id, 'globuspioner', 'pa_vendor', true );
  308.  
  309.             // Attridutes value
  310.             $thedata = array(
  311.                 'pa_application'    => array(
  312.                     'name'          => 'pa_application',
  313.                     'value'         => 'termo-perenos',
  314.                     'is_visible'    => '1',
  315.                     'is_variation'  => '0',
  316.                     'is_taxonomy'   => '1'
  317.                 ),
  318.                 'pa_country'    => array(
  319.                     'name'          => 'pa_country',
  320.                     'value'         => 'ukrayina',
  321.                     'is_visible'    => '1',
  322.                     'is_variation'  => '0',
  323.                     'is_taxonomy'   => '1'
  324.                 ),
  325.                 'pa_originality'    => array(
  326.                     'name'          => 'pa_originality',
  327.                     'value'         => 'oryginal',
  328.                     'is_visible'    => '1',
  329.                     'is_variation'  => '0',
  330.                     'is_taxonomy'   => '1'
  331.                 ),
  332.                 'pa_vendor'    => array(
  333.                     'name'          => 'pa_vendor',
  334.                     'value'         => 'globuspioner',
  335.                     'is_visible'    => '1',
  336.                     'is_variation'  => '0',
  337.                     'is_taxonomy'   => '1'
  338.                 )
  339.             );
  340.             update_post_meta( $post_id,'_product_attributes', $thedata);
  341.  
  342.             update_post_meta( $post_id, '_visibility', 'visible' );
  343.             update_post_meta( $post_id, '_stock_status', 'instock');
  344.             update_post_meta( $post_id, 'total_sales', '0');
  345.             update_post_meta( $post_id, '_downloadable', 'no');
  346.             update_post_meta( $post_id, '_virtual', 'yes');
  347.             update_post_meta( $post_id, '_regular_price', $price );
  348.             update_post_meta( $post_id, '_sale_price', "" );
  349.             update_post_meta( $post_id, '_purchase_note', "" );
  350.             update_post_meta( $post_id, '_featured', "no" );
  351.             update_post_meta( $post_id, '_weight', "" );
  352.             update_post_meta( $post_id, '_length', "" );
  353.             update_post_meta( $post_id, '_width', "" );
  354.             update_post_meta( $post_id, '_height', "" );
  355.             update_post_meta( $post_id, '_sku', $sku);
  356.             update_post_meta( $post_id, '_product_attributes', array());
  357.             update_post_meta( $post_id, '_sale_price_dates_from', "" );
  358.             update_post_meta( $post_id, '_sale_price_dates_to', "" );
  359.             update_post_meta( $post_id, '_price', $price );
  360.             update_post_meta( $post_id, '_sold_individually', "" );
  361.             update_post_meta( $post_id, '_manage_stock', "no" );
  362.             update_post_meta( $post_id, '_backorders', "no" );
  363.             update_post_meta( $post_id, '_stock', "" );
  364.  
  365.             //Images
  366.             update_post_meta( $post_id, '_product_image_gallery', implode(',',$images));
  367.         }
  368.  
  369.     }
  370. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement