Answer the question
In order to leave comments, you need to log in
How to upload csv to Yandex audience via API?
Good afternoon! There is a task on php to create a segment in the Yandex audience. The following instruction is described in the Yandex api https://yandex.ru/dev/audience/doc/segments/upload...
I am
sending a file through the library https://github.com/mervick/curl-helper
$output = CurlHelper::factory(self::API . "management/segments/upload_csv_file")
->setHeaders([
'Content-type' => CurlHelper::MIME_FORM_DATA,
'Authorization' => 'OAuth ' . $this->OAuthToken,
])
->putFileRaw(basename($file), file_get_contents($file), basename($file), 'application/octet-stream')
->exec();
Answer the question
In order to leave comments, you need to log in
The refusal to use the library and the use of the following code helped
class Curl
{
/**
* Отправить файл
* @param string $url
* @param string $pathToFile
* @param string $type
* @param array $headers
* @return false|string
*/
public static function sendFile(string $url, string $pathToFile, string $type = 'text/plain', array $headers = [])
{
$boundary = uniqid();
$filename = basename($pathToFile);
$calls = join(PHP_EOL, explode("\n", file_get_contents($pathToFile)));
$data = "--------------------------{$boundary}\x0D\x0A";
$data .= "Content-Disposition: form-data; name=\"file\"; filename=\"{$filename}\"\x0D\x0A";
$data .= "Content-Type: {$type}\x0D\x0A\x0D\x0A";
$data .= $calls . "\x0A\x0D\x0A";
$data .= "--------------------------{$boundary}--";
$headers['Content-Type'] = "multipart/form-data; boundary=------------------------{$boundary}";
$headers['Content-Length'] = strlen($data);
$resHeaders = [];
foreach ($headers as $key=>$head) {
$resHeaders[] = $key . ': ' . $head;
}
return self::request($url, $data, $resHeaders);
}
/**
* Запрос
* @param string $url
* @param string $data
* @param array $headers
* @param string $method
* @return false|string
*/
public static function request(string $url, string $data, array $headers, string $method = 'POST')
{
$opt = [
'http' => [
'method' => $method,
'content' => $data,
'header' => join(PHP_EOL, $headers),
],
];
$context = stream_context_create($opt);
return file_get_contents($url, false, $context);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question