A
A
Anton Seredny2016-04-26 16:11:20
PHP
Anton Seredny, 2016-04-26 16:11:20

How to change encoding from utf-8 to windows-1251 for serialized array or json?

Good afternoon, there is a function that forms the array I need, serializes it and puts it in a text file. But the site is running on UTF-8.

// Сама функция для формирования файла
function makePost() {

// Получим посты
global $post; $args = array( 'posts_per_page' => 3,  'category' => 3 ); $myposts = get_posts( $args );

// Составим нужный нам массив
$tofile = [];
$i_count = 0;

foreach ($myposts as $item) {
  $tofile[$i_count]['title'] = $item->post_title;
  $tofile[$i_count]['link'] =  $item->guid;
  $tofile[$i_count]['image'] = get_the_post_thumbnail_url( $item->ID );
  $tofile[$i_count]['text'] = $item->post_excerpt;

  $i_count++;
}

$tofile = serialize($tofile);

// Открыть текстовый файл и запишем туда сериализованный массив
  $f = fopen("textfile.txt", "w");
  file_put_contents($f, '');

  // Записать строку текста
  fwrite($f, $tofile); 

  // Закрыть текстовый файл
  fclose($f);
}

I'm pulling this text file from another site (site encoded 1251) and using unserialize I use it as an array and output the array...
<?php

function get_yposts() {

// Источник для парсера
$url ='http://site.info/textfile.txt';

$ch = curl_init(); // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s

$doc = curl_exec($ch);
$posts = unserialize($doc);
$posts = iconv('utf-8', 'windows-1251', $posts);


foreach ($posts as $post) {
echo "<div class='yt-post'>";
echo "<a class='yt-title' href='".$post['link']."'>";
echo "<img class='yt-post' src='".$post['image']."'>";
echo "</a>";
echo "<a class='yt-title' href='".$post['link']."'>".$post['title']."</a>";
echo "<p class='yt-text'>".$post['text']."</p>";

echo "</div>";

}

}

get_yposts();


?>

Kryakozyabry alone. I don't understand how to use iconv in this case.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey, 2016-04-26
@smidl

If you are pulling data from a site where the encoding is Windows-1251, then swap the encodings in iconv to convert Win1251 -> UTF8, and not vice versa as it is now.

V
Vladimir, 2016-04-26
Khatter @mrKhatter

Catch! ;)

...
$posts = iconv( 'windows-1251', 'utf-8', $posts);
...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question