123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- <?php
- namespace Ku\Spider;
- use Dever;
- class Handle
- {
- public function createProduct($id = false)
- {
- $id = Dever::input('id', $id);
- $product = Dever::db('ku/product')->one($id);
- $spider = $this;
- $param = array();
- if ($product && $product['link']) {
- $update = false;
- if (!$product['name'] || !$product['pic'] || !$product['price']) {
- $update = true;
- }
- if ($update) {
- $data = $spider->get($product['link']);
- if ($data) {
- $param['name'] = $product['name'] ? $product['name'] : $data['name'];
- $param['pic'] = $product['pic'] ? $product['pic'] : $this->pic($data);
- $param['price'] = $product['price'] ? $product['price'] : $data['price'];
- }
- }
- Dever::config('base')->hook = true;
- if ($param) {
- $param['where_id'] = $id;
- Dever::db('ku/product')->update($param);
- }
- }
- }
- private function pic($result)
- {
- if (isset($result['pic']) && $result['pic']) {
- if (!strstr($result['pic'], 'http')) {
- $result['pic'] = 'http:' . $result['pic'];
- }
- $pic = Dever::load('upload/save')->copy($result['pic']);
- if (isset($pic['url']) && $pic['url']) {
- $result['pic'] = $pic['url'];
- }
- }
- return $result['pic'];
- }
- public function get($link)
- {
- $type = $this->getType($link);
- if ($type) {
- $link = trim($link, "\r\n");
- $link = $type->link($link);
- $data = $this->filter(Dever::curl($link));
- $result = $this->rule($type->rule(), $data, $type);
- return $result;
- }
- return false;
- }
- private function getType($link)
- {
- $type = '';
- if (strpos($link, 'taobao.com')) {
- $type = 'taobao';
- } elseif (strpos($link, 'tmall.com')) {
- $type = '';
- } elseif (strpos($link, 'youzan.com')) {
- $type = 'youzan';
- }
- if (!$type) {
- return false;
- }
- return Dever::load('ku/spider/' . $type);
- }
- private function rule($rule, $data, $type)
- {
- $result = array();
- foreach ($rule as $key => $value) {
- $m = 1;
- if (is_array($value)) {
- $m = $value[1];
- $value = $value[0];
- }
- if (strstr($value, '/')) {
- $value = str_replace('/', '\/', $value);
- }
- preg_match_all('/'.$value.'/i', $data, $matches);
- $result[$key] = '';
- if (isset($matches[$m][0])) {
- $result[$key] = trim($matches[$m][0]);
- $result[$key] = $type->replace($key, $result[$key]);
- $result[$key] = str_replace(array(' ', "\t"), '', $result[$key]);
- }
- }
-
- return $result;
- }
- private function filter($string)
- {
- $encode = mb_detect_encoding($string, array('GB2312','GBK','UTF-8'));
- $config = array('GB2312', 'GBK', 'EUC-CN', 'CP936');
- if (in_array($encode, $config)) {
- $string = mb_convert_encoding($string, 'UTF-8', 'GBK');
- }
- $string = str_replace(PHP_EOL, '', $string);
- return $string;
- }
- }
|