Яндекс товары или турбо страницы для OpenCart
Так как готового решения не нашел для нового сервиса от Яндекса — Поиск по товарам. А так как был самописный файл для турбо страниц для OpenCart, решил его немного переделать.
Для начала создадим какую то папку в корне вашего сайта, допустим это будет папка с названием yashop.
В ней сделаем два файла, один который будет подключаться к вашей базе данных, а другой собственно генерировать файл yml для магазина на основе OpenCart.
Первый файл db_con.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <?php class DB_CONNECT { public function __construct() {} public function __destruct() {} public function connect() { // Connecting to mysql database $link = mysqli_connect(<адрес сервера>, <имя пользователя>, <пароль>, <имя базы данных>); if (!$link) { // echo "Error: Unable to connect to MySQL." . PHP_EOL; // echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL; // echo "Debugging error: " . mysqli_connect_error() . PHP_EOL; exit; } mysqli_set_charset($link, "utf8"); // returing connection cursor return $link; } } |
Пропишем в него данные для подключения к базе данных
<адрес сервера>, <имя пользователя>, <пароль>, <имя базы данных>
Затем создадим непосредственно сам файл который будет обрабатывать и генерировать файл yml — ya_shop.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | <?php $yGenerator = new YGenerator(); $xml = $yGenerator->getYml(); Header('Content-type: text/xml'); print($xml->asXML()); class YGenerator { public function getYml() { require_once __DIR__ . '/db_con.php'; $db = new DB_CONNECT(); $con = $db->connect(); $xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><yml_catalog/>'); $dt = date("Y-m-d"); $tm = date("H:i"); $xml->addAttribute("date", $dt . ' ' . $tm); $shop = $xml->addChild('shop'); $shop->addChild('name', "Название сайт"); $shop->addChild('company', "Название компании"); $shop->addChild('url', "https://адрес сайта/"); $shop->addChild('version', "10.02"); $siteurl = 'https://адрес сайта'; $currencies = $shop->addChild('currencies'); $currency = $currencies->addChild('currency'); $currency->addAttribute("id", "RUB"); $currency->addAttribute("rate", "1"); $categories = $shop->addChild('categories'); $sql = "SELECT `category_id`, `name` FROM `oc_category_description` WHERE 1 ORDER BY `category_id`"; $result = $con->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $category = $categories->addChild('category', $row['name']); $category->addAttribute("id", $row['category_id']); $parentId = $this->getParentIdCategory($con, $row['category_id']); if ($parentId != 0) { $category->addAttribute("parentId", $parentId); } } } $offers = $shop->addChild('offers'); $sql = "SELECT * FROM `oc_product` WHERE `status` > 0 and `image`!=''"; $result = $con->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $productId = $row['product_id']; $manufacturerId = $row['manufacturer_id']; $stock_quantity = $row['quantity']; $listAttributes = array(); $ddddddddd = 'product_id=' . $productId; $sql3 = "SELECT * FROM `oc_url_alias` WHERE `query` = '" . $ddddddddd . "'"; $result3 = $con->query($sql3); //$row3 = $result3->fetch_assoc(); //print_r($row3['keyword']); if ($result3->num_rows > 0) { $row3 = $result3->fetch_assoc(); $valueUrl = $row3['keyword']; $textUrl = $siteurl.'' . $valueUrl . '.html?utm_source=yandex_shop'; } else { $textUrl = $siteurl.''index.php?route=product/product&product_id=' . $row['product_id'] . '?utm_source=yandex_shop'; } // while ($row3 = $result3->fetch_assoc()) { // $data = array(); // $nameAttribute = $this->getNameAttributeById($con, $row3['attribute_id']); // $data['nameAttribute'] = $nameAttribute; // $valueAttribute = $row3['text']; // $data['valueAttribute'] = $valueAttribute; // $data['sortOrder'] = $this->getAttributeSortOrder($con, $row3['attribute_id']); // array_push($listAttributes, $data); //} //checking, how many attributes in product && if exist image of products //don't adding the product if min attributes // if (count($listAttributes) > 4 && strlen($row['image']) > 4) { $offer = $offers->addChild('offer'); $offer->addAttribute("id", $row['product_id']); $offer->addAttribute("available", "true"); $offer->addChild('url', $textUrl); $offer->addChild('price', round($row['price'], 2)); $offer->addChild('currencyId', 'RUB'); $offer->addChild('categoryId', $this->getCategoryOfProduct($con, $row['product_id'])); $img = $siteurl.''image/' . $row['image']; $offer->addChild('picture', $img); $vendorName = $this->getVendorName($con, $manufacturerId); if (!empty($vendorName)) { $offer->addChild('vendor', $vendorName); } else { $offer->addChild('vendor', 'Россия'); } //$offer->addChild('gtin', $row['upc']); //$offer->addChild('stock_quantity', $stock_quantity); //$offer->addChild('store', "false"); $offer->addChild('pickup', "true"); $offer->addChild('delivery', "true"); $sql2 = "SELECT * FROM `oc_product_description` WHERE `product_id` = '$productId'"; $result2 = $con->query($sql2); if ($result2->num_rows > 0) { while ($row2 = $result2->fetch_assoc()) { // $des_text = str_replace("<ul>", ".", $row2['description']); // $des_text = str_replace("</li>", ".", $des_text); // $des_text = str_replace("</li><li>", ".", $des_text); // $des_text = str_replace("..", ". ", $des_text); //$des_text = str_replace("</ul>", ". ", $des_text); //$des_text = $row2['description']; // $text = $this->removeLi($row2['description']); $text = $row2['description']; //$text = $this->removeTags($text); $name = $offer->addChild('name', $row2['name']); $shortdesc = 'В нашем магазине Вы сможете заказать ' . $name . ' по лучшим ценам с доставкой по Москве и Московской области.'; if (strlen(trim($text)) == 0) { $offer->addChild('description', $shortdesc); } else { //$text = mb_substr($text, 0, 250,'UTF-8'); // обрезаем и работаем со всеми кодировками и указываем исходную кодировку //$position = mb_strrpos($text, ' ', 'UTF-8'); // определение позиции последнего пробела. Именно по нему и разделяем слова //$text = mb_substr($text, 0, $position, 'UTF-8'); // Обрезаем переменную по позиции $offer->addChild('description', $text); } } } // sort array by `sortOrder` // for ($i = 0; $i < count($listAttributes); $i++) { // for ($j = $i + 1; $j < count($listAttributes); $j++) { // if ($listAttributes[$i]['sortOrder'] > $listAttributes[$j]['sortOrder']) { // $temp = $listAttributes[$j]; // $listAttributes[$j] = $listAttributes[$i]; // $listAttributes[$i] = $temp; // } // } // } ### Adding attributes // for ($i = 0; $i < count($listAttributes); $i++) { // $valueAttribute = trim($listAttributes[$i]['valueAttribute']); // $valueAttribute = $this->cutExtraCharacters($valueAttribute); // $param = $offer->addChild('param', $valueAttribute); // $param->addAttribute('name', $listAttributes[$i]['nameAttribute']); // } //} // } } } return $xml; } private function cutExtraCharacters($str) { $cyr = [ ' кг', ' л', ' Вт', ' куб. м/ч', ' см', ' дБ', ]; $str = str_replace($cyr, '', $str); return $str; } private function removeLi($des_text) { $order = array("<li>", "<ul>", "<", "li>"); $replace = '.'; //$des_text = htmlspecialchars($des_text); $des_text = str_replace($order, $replace, $des_text); // $des_text = str_replace("<ul><li>",". ",$des_text); // $des_text = str_replace("</li><li>",". ",$des_text); // $des_text = str_replace("<li>",". ",$des_text); // $des_text = str_replace("<ul>", ".", $des_text, UTF-8); // $des_text = str_replace("</li>",".",$des_text); // $des_text = str_replace("</li><li>",".",$des_text); // $des_text = str_replace("..",". ",$des_text); //$str = htmlspecialchars($str); // $des_text = preg_replace('/<meta([^&]*)\/>/', ' ', $des_text); // $des_text = preg_replace('/&(?!#?[a-z0-9]+;)/', ' ', $des_text); // $des_text = preg_replace('/<[^>]*>/', '', $des_text); return $des_text; } private function getAttributeSortOrder($con, $attributeId) { $sql = "SELECT `sort_order` FROM `oc_attribute` WHERE `attribute_id` = '$attributeId'"; $result = $con->query($sql); $sortOrder = 0; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $sortOrder = $row['sort_order']; } } if ($sortOrder == 0) { $sortOrder = 50; } return $sortOrder; } /** * Getting name of the attribute by id * @param $con * @param $attributeId * @return string */ private function getNameAttributeById($con, $attributeId) { $sql = "SELECT `name` FROM `oc_attribute_description` WHERE `attribute_id` = '$attributeId'"; $result = $con->query($sql); $name = ''; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $name = $row['name']; } } return $name; } private function removeTags($str) { //$str = htmlspecialchars($str); $str = preg_replace('/<meta([^&]*)\/>/', '', $str); $str = preg_replace('/&(?!#?[a-z0-9]+;)/', '&', $str); $str = preg_replace('/<[^>]*>/', '.', $str); $str = str_replace('P.S. В случае отсутствия товара, оставьте заявку на нашем сайте!', '', $str); $str = str_replace('Характеристики и комплектация товара могут изменяться производителем без уведомления', '', $str); $str = strip_tags($str); // $str = $str.replaceAll("<[^>]*>", ""); return $str; } private function getCategoryOfProduct($con, $productId) { $sql = "SELECT `category_id` FROM `oc_product_to_category` WHERE `product_id` = '$productId'"; $result = $con->query($sql); $categoryId = 0; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $categoryId = $row['category_id']; } } return $categoryId; } private function getParentIdCategory($con, $codeGroup) { $sql = "SELECT `parent_id` FROM `oc_category` WHERE `category_id` = '$codeGroup'"; $result = $con->query($sql); $parentId = 0; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $parentId = $row['parent_id']; } } return $parentId; } private function getVendorName($con, $manufacturerId) { $sql = "SELECT `name` FROM `oc_manufacturer` WHERE `manufacturer_id` = '$manufacturerId'"; $result = $con->query($sql); $nameVendor = ''; if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $nameVendor = $row['name']; } } return $nameVendor; } } |
Много чего лишнего закомментировано, но может пригодиться кому ни будь.
Теперь вставим этот файл в сервис https://webmaster.yandex.ru/ в раздел Товары и предложения -> источники данных.
просто и работает