Перейти к содержимому


Получение данных из ВК


Сообщений в теме: 6

#1 BorisSuvorov

    Участник

  • Пользователи
  • PipPip
  • 11 сообщений

Отправлено 06 Сентябрь 2016 - 03:43

Здравствуйте! Стоит задача при сохранении id пользователя ВК, подтягивать его данные из соцсети. Локально все работает. Когда вставляют код в "Клиентскую базу" выдает ошибку:


Ошибка в вычислении.

Артисты.Отображение поля: Массив ВК :

1: $fields = [
2: 'photo_id',
syntax error, unexpected '['



Подскажите, с чем это может быть связано? Синтаксис, вроде, правильный


$fields = [
	'photo_id',
	'verified',
	'sex',
	'bdate',
	'city',
	'country',
	'home_town',
	'has_photo',
	'photo_50',
	'photo_100',
	'photo_200_orig',
	'photo_200',
	'photo_400_orig',
	'photo_max',
	'photo_max_orig',
	'online',
	'lists',
	'domain',
	'has_mobile',
	'contacts',
	'site',
	'education',
	'universities',
	'schools',
	'status',
	'last_seen',
	'followers_count',
	'common_count',
	'occupation',
	'nickname',
	'relatives',
	'relation',
	'personal',
	'connections',
	'exports',
	'wall_comments',
	'activities',
	'interests',
	'music',
	'movies',
	'tv',
	'books',
	'games',
	'about',
	'quotes',
	'can_post',
	'can_see_all_posts',
	'can_see_audio',
	'can_write_private_message',
	'can_send_friend_request',
	'is_favorite',
	'is_hidden_from_feed',
	'timezone',
	'screen_name',
	'maiden_name',
	'crop_photo',
	'is_friend',
	'friend_status',
	'career',
	'military',
	'blacklisted',
	'blacklisted_by_me'
];

$request_params = [
	'user_ids' => $line['id пользователя'],
	'name_case' => 'nom',
	'fields' => implode(',',$fields),
	'access_token' => 'тут_токен'
];
$url = "https://api.vk.com/method/users.get?".http_build_query($request_params);
$result = file_get_contents($url);
$line['Массив ВК'] = $result;


#2 CbCoder

    Активный участник

  • Программист ООО "КБ"
  • PipPipPip
  • 8 759 сообщений
  • Пол:Мужчина
  • Город:Казань

Отправлено 06 Сентябрь 2016 - 09:47

Синтаксис с квадратными скобками для присвоения массивов работает только с PHP 5.4. Если вы вставляете данный код в аккаунт на SaaS, то он там может не работать, т.к. версия PHP там 5.3, насколько знаю. Необходимо использовать старый вариант с оператором array:

$fields = array(
	    'photo_id',
	    'verified',
	    'sex',
	    'bdate',
	    'city',
	    'country',
	    'home_town',
	    'has_photo',
	    'photo_50',
	    'photo_100',
	    'photo_200_orig',
	    'photo_200',
	    'photo_400_orig',
	    'photo_max',
	    'photo_max_orig',
	    'online',
	    'lists',
	    'domain',
	    'has_mobile',
	    'contacts',
	    'site',
	    'education',
	    'universities',
	    'schools',
	    'status',
	    'last_seen',
	    'followers_count',
	    'common_count',
	    'occupation',
	    'nickname',
	    'relatives',
	    'relation',
	    'personal',
	    'connections',
	    'exports',
	    'wall_comments',
	    'activities',
	    'interests',
	    'music',
	    'movies',
	    'tv',
	    'books',
	    'games',
	    'about',
	    'quotes',
	    'can_post',
	    'can_see_all_posts',
	    'can_see_audio',
	    'can_write_private_message',
	    'can_send_friend_request',
	    'is_favorite',
	    'is_hidden_from_feed',
	    'timezone',
	    'screen_name',
	    'maiden_name',
	    'crop_photo',
	    'is_friend',
	    'friend_status',
	    'career',
	    'military',
	    'blacklisted',
	    'blacklisted_by_me'
);
$request_params = array(
	    'user_ids' => $line['id пользователя'],
	    'name_case' => 'nom',
	    'fields' => implode(',',$fields),
	    'access_token' => 'тут_токен'
);
$url = "https://api.vk.com/method/users.get?".http_build_query($request_params);
$result = file_get_contents($url);
$line['Массив ВК'] = $result;


#3 akrivola

    Новичок

  • Пользователи
  • Pip
  • 1 сообщений

Отправлено 08 Сентябрь 2016 - 11:54

Борис, скажите, а Вам удалось реализовать это? У меня скрипт отрабатывает, но ничего не происходит. Запрос к API формируется правильный, в строку браузера вставлял - работает.

#4 BorisSuvorov

    Участник

  • Пользователи
  • PipPip
  • 11 сообщений

Отправлено 11 Сентябрь 2016 - 02:32

Просмотр сообщенияakrivola (08 Сентябрь 2016 - 11:54) писал:

Борис, скажите, а Вам удалось реализовать это? У меня скрипт отрабатывает, но ничего не происходит. Запрос к API формируется правильный, в строку браузера вставлял - работает.

Та же история, пока не разобрался в чем дело. Если найду решение - отпишусь тут

Сообщение отредактировал BorisSuvorov: 11 Сентябрь 2016 - 02:32


#5 BorisSuvorov

    Участник

  • Пользователи
  • PipPip
  • 11 сообщений

Отправлено 14 Сентябрь 2016 - 10:38

Добрый день! Может кто-то сможет подсказать, что не так делаю - локально все отлично работает, все возвращает как надо. Вставляю в Клиентскую Базу - но ничего не происходит, хотя ошибок тоже не выдает. Заранее спасибо!

$userid = $line['vkid'];
$fields = array (
    'photo_id',
    'verified',
    'sex',
    'bdate',
    'city',
    'country',
    'home_town',
    'has_photo',
    'photo_200',
    'online',
    'lists',
    'domain',
    'has_mobile',
    'contacts',
    'site',
    'status',
    'last_seen',
    'followers_count',
    'common_count',
    'nickname',
    'relatives',
    'relation',
    'personal',
    'connections',
    'exports',
    'wall_comments',
    'activities',
    'interests',
    'about',
    'can_post',
    'can_see_all_posts',
    'can_see_audio',
    'can_write_private_message',
    'can_send_friend_request',
    'screen_name',
    'maiden_name',
    'counters',
    'first_name_gen',
    'last_name_gen',
);

$request_params = array (
    'user_ids' => $userid,
    'name_case' => 'nom',
    'fields' => implode(',',$fields),
    'access_token' => 'тут_токен'
);
$url = "https://api.vk.com/method/users.get?".http_build_query($request_params);
$json = file_get_contents($url);
$json_decode = json_decode($json , true);
$line['Имя'] = $json_decode["response"][0]["first_name"]; //Имя


#6 CbCoder

    Активный участник

  • Программист ООО "КБ"
  • PipPipPip
  • 8 759 сообщений
  • Пол:Мужчина
  • Город:Казань

Отправлено 14 Сентябрь 2016 - 11:42

Функция file_get_contents не является надежным источником данных в случае получения их по url. Надежно она работает только с локальными файлами. Для http лучше использовать специальные способы, например cURL

#7 BorisSuvorov

    Участник

  • Пользователи
  • PipPip
  • 11 сообщений

Отправлено 16 Сентябрь 2016 - 10:09

Спасибо! Наконец, разобрался, все заработало. Первый раз - оказалось, выбило капчу - раз ввел, теперь все как надо работает. Кому интересно, вот рабочий код:

$userfirst = $line['VK (личная)']; // получаем короткое имя из url
$whatis  = substr($userfirst, 0,5);
if($whatis="https"){
$userid  = substr($userfirst, 15);
} elseif ($whatis="http"){
	$userid  = substr($userfirst, 14);
} elseif ($whatis="vk.co"){
	$userid  = substr($userfirst, 7);
}
$fields = array (
	'photo_id',
	'verified',
	'sex',
	'bdate',
	'city',
	'country',
	'home_town',
	'has_photo',
	'photo_200',
	'online',
	'lists',
	'domain',
	'has_mobile',
	'contacts',
	'site',
	'status',
	'last_seen',
	'followers_count',
	'common_count',
	'nickname',
	'relatives',
	'relation',
	'personal',
	'connections',
	'exports',
	'wall_comments',
	'activities',
	'interests',
	'about',
	'can_post',
	'can_see_all_posts',
	'can_see_audio',
	'can_write_private_message',
	'can_send_friend_request',
	'screen_name',
	'maiden_name',
	'counters',
	'first_name_gen',
	'last_name_gen',
);



$request_params = array (
	'user_ids' => $userid,
	'name_case' => 'nom',
	'fields' => implode(',',$fields),
	'access_token' => 'сюда вставляем токен',
   // 'captcha_sid' => 380354804047, эти два поля использовал один раз для ввода капчи, больше не потребовались
//   'captcha_key'=>'vz5qxqa'
);

$url = "https://api.vk.com/method/users.get?".http_build_query($request_params);



$ch = curl_init($url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,true);
$json = curl_exec($ch);
curl_close($ch);

$json_decode = json_decode($json , true);


$line['id VK'] = $json_decode["response"][0]["uid"]; //Id пользователя
$line['Имя'] = $json_decode["response"][0]["first_name"]; //Имя



$line['Фамилия'] = $json_decode["response"][0]["last_name"]; //Фамилия
if(!$line['Артист']){
$line['Артист']=$line['Имя'] ." ".$line['Фамилия'] ;
}
$gender = $json_decode["response"][0]["sex"]; //Пол
if($gender==0) {
	$line['Пол'] = "Не известно";
  } elseif ($gender==1) {
	$line['Пол'] = "Женский";
} elseif ($gender==2) {
	$line['Пол'] = "Мужской";
}
$line['Дата рождения'] = $json_decode["response"][0]["bdate"]; //Дата рождения





$cityid = $json_decode["response"][0]["city"]; //Получаем id города
$city_params = array (
	'city_ids' => $cityid,
);
$cityurl= "https://api.vk.com/method/database.getCitiesById?".http_build_query($city_params);
//$cityjson = file_get_contents($cityurl);
$cityculr= curl_init($cityurl);
curl_setopt($cityculr,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($cityculr,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($cityculr,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($$cityculr,CURLOPT_FOLLOWLOCATION,true);
$cityjson = curl_exec($cityculr);
curl_close($cityculr);
$city_json_decode = json_decode($cityjson , true);
$line['Город'] = $city_json_decode["response"][0]["name"]; //Выводим название города




$countryid = $json_decode["response"][0]["country"]; //Получаем id страны
$country_params = array (
	'country_ids' => $countryid,
);
$countryurl= "https://api.vk.com/method/database.getCountriesById?".http_build_query($country_params);
//$countryjson = file_get_contents($countryurl);
$countr = curl_init($countryurl);
curl_setopt($countr,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($countr,CURLOPT_SSL_VERIFYHOST,false);
curl_setopt($countr,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($countr,CURLOPT_FOLLOWLOCATION,true);
$countryjson = curl_exec($countr);
curl_close($countr);
$country_json_decode = json_decode($countryjson , true);
$line['Страна'] = $country_json_decode["response"][0]["name"]; //Выводим название страны




$line['Фото'] = "<img src=".$json_decode["response"][0]["photo_200"].">"; //Ссылка на фото
if(!$line['Телефон']){
$line['Телефон'] = $json_decode["response"][0]["mobile_phone"]; //Телефон
}
if(!$line['Сайт артиста']){
$line['Сайт артиста'] = $json_decode["response"][0]["site"]; //Сайт
}
$twittet = $json_decode["response"][0]["twitter"]; //Твиттер
if($twittet){
$line['Twitter'] = "https://twitter.com/".$twittet;
}

$insta = $json_decode["response"][0]["instagram"]; //Инстаграмм
if($insta){
$line['Instagram'] = "https://www.instagram.com/".$insta;
}

$last_seen_code = $json_decode["response"][0]["last_seen"]["time"]; //Последний визит
$line['Последний онлайн ВК'] = date("y-m-d h:i:s", $last_seen_code );
$line['Интересы'] = $json_decode["response"][0]["interests"]; //Интересы
$line['Деятельность'] = $json_decode["response"][0]["activities"]; //Деятельность

$superstar = $json_decode["response"][0]["verified"]; //Звезда
if($superstar==0) {
	$line['Звезда'] = "Нет";
} elseif ($superstar==1) {
	$line['Звезда'] = "Да";
}

$friends = $json_decode["response"][0]["counters"]["friends"]; //Число Друзей
$followers = $json_decode["response"][0]["counters"]["followers"]; //Число подписчиков
$line['VK (к-во подп. Личной Страницы)'] = $friends + $followers; //Друзья + подписчики

$name_gen = $json_decode["response"][0]["first_name_gen"]; //Имя в родительном падеже
$last_name_gen = $json_decode["response"][0]["last_name_gen"]; //Фамилия в родительном падеже
$gen = $name_gen . " " . $last_name_gen;
$line['Имя для рассылки (в род. падеже)'] = $gen;

Сообщение отредактировал BorisSuvorov: 16 Сентябрь 2016 - 10:13






Количество пользователей, читающих эту тему: 2

0 пользователей, 2 гостей, 0 анонимных