export csv catch null value symfony 2 - symfony

I have some troubles with an export to csv. In my table I have some null value and I can't find out how to catch them.
public function exportCSVAction()
{
$results = $this->getDoctrine()->getManager()
->getRepository('MyRepoBundle:Cronexecution')->findAll();
$response = new StreamedResponse();
$response->setCallback(
function () use ($results) {
$handle = fopen('php://output', 'r+');
foreach ($results as $row) {
if (!($row->getNbLineIn()) && !($row->getNbLineOut())) {
$delContact = (($row->getNbLineIn()) - ($row->getNbLineOut()));
}
else{
$delContact="Unknown";
}
$data = array(
$row->getClient(),
$row->getDealingName(),
$row->$delContact,
);
fputcsv($handle, $data);
}
fclose($handle);
}
);
$response->headers->set('Content-Type', 'application/force-download');
$response->headers->set('Content-Disposition', 'attachment; filename="export.csv"');
return $response;
}
When I delete the $row->$delContact the csv export work cause there isn't null value but when I let it I got a "This site can’t be reached" error.
So I tried to catch when it's null with 2 or 3 different method but impossible to figure it out.
Thanks for your help

Change according to bellow code :
$data = array(
$row->getClient(),
$row->getDealingName(),
$delContact,
);

Related

Update post terms in each languages by code

who can hellp with this, i need create post from code, by wp_insert_post
function, so what is going on:
I creating post on each existing laguages, then i update all needed fields and i need to set post term depened of current language.
I have terms (shelters) https://prnt.sc/pklSXojB2jZj - i need that post set to current lang shelter while create, but after creating i got - https://prnt.sc/pz2jFEq1OAMP , 2 posts set in one lang terms. Maybe who know whats goes wrong, below i provided 2 functions who do these actions, Thanks in advance:
function add_pet($form_data, $ready_data, $update_meta = false) {
$allLang = pll_languages_list();
if ($allLang) {
$postsArr = array();
foreach ($allLang as $lang) {
//Add new pet
$post_id = wp_insert_post(array(
'post_title' => $form_data['pet_name'],
'post_status' => 'publish',
'post_author' => $form_data['user_id'],
'post_type' => 'pets',
));
//Check if post created, update all needed fields, and update post terms (shelter)
if ($post_id) {
//Get all translation of term
$shelter_id = pll_get_term(intval($form_data['shelter']), $lang);
$update_meta['shelter'] = $shelter_id;
//In this function we update those terms
$update_success = update_pets_fields($post_id, $ready_data, $update_meta);
$postsArr[$lang] = $post_id;
pll_set_post_language($post_id, $lang);
$postDate = get_post($post_id)->post_date;
$unixDate = strtotime($postDate);
update_post_meta($post_id, 'pet_update_date', $unixDate);
}
}
//Save post translation
if ($postsArr) {
pll_save_post_translations($postsArr);
}
//Old code
// foreach ($allLang as $lang) {
// $cat_id = pll_get_term(intval($form_data['kind_of_animal']), $lang);
// $shelter_id = pll_get_term(intval($form_data['shelter']), $lang);
// $post_id = $postsArr[$lang];
// $update_meta['post_category'] = $cat_id;
// $update_meta['shelter'] = $shelter_id;
// $update_success = update_pets_fields($post_id, $ready_data, $update_meta);
// }
}
if (is_wp_error($post_id)) {
wp_send_json_error($post_id->get_error_message());
}
if ($update_success) {
wp_send_json_success('Post was created.');
} else {
wp_send_json_error('Post was not created.');
}
}
And function who update field
/Update pets fields
function update_pets_fields($post_id, $data, $update_meta = false) {
if (!$post_id) return;
//Update post meta data not acf
if (isset($update_meta) && !empty($update_meta['title'])) {
$post_update = array(
'ID' => $post_id,
'post_title' => $update_meta['title']
);
$result = wp_update_post($post_update);
if (is_wp_error($result)) {
wp_send_json_error('Fields was not updated');
}
}
if (isset($update_meta['shelter']) && !empty($update_meta['shelter']) && intval($update_meta['shelter'])) {
wp_remove_object_terms($post_id, 'uncategorized', 'sholters');
$shelter_id = intval($update_meta['shelter']);
wp_set_post_terms($post_id, array($shelter_id), 'sholters');
if (is_wp_error($result)) {
wp_send_json_error('Term not updated');
}
}
if (isset($update_meta['post_category']) && !empty($update_meta['post_category']) && intval($update_meta['post_category'])) {
wp_remove_object_terms($post_id, 'uncategorized', 'category');
wp_set_post_categories($post_id, intval($update_meta['post_category']));
if (is_wp_error($result)) {
wp_send_json_error('Category not updated');
}
}
if (isset($update_meta['thumbnail']) && !empty($update_meta['thumbnail']) && intval($update_meta['thumbnail'])) {
set_post_thumbnail($post_id, intval($update_meta['thumbnail']));
}
if (is_null($data)) {
wp_send_json_error('No data.');
}
foreach ($data as $field) {
if ($field[3] === 'where_is') {
$field_array['field_62169d3cffb5b'] = array(
$field[2] => $field[1],
);
} else {
$field_array = array(
$field[2] => $field[1],
);
}
if (!empty($field[1])) {
$result = update_field('field_621696a7ffb4e', $field_array, $post_id);
}
}
if ($result) {
return false;
} else {
return true;
}
}
I try update it in diferent variants but it does't work, i check ids that come in args all ids is right and all posts ids is right.But on at the exit we got 2 posts in 1 term

csv export not working with symfony 3

I try to do a csv export on my symfony project and i think that something is wrong because nothing happens and i have no error...??
public function exportCsv($customers)
{
$fileName = "export_" . date("d_m_Y") . ".csv";
$response = new StreamedResponse();
$response->setCallback(function() use ($customers){
$handle = fopen('php://output', 'w+');
// Nom des colonnes du CSV
fputcsv($handle, array('Name',
'Adress',
'City',
'Code'
), ';');
//Champs
foreach ($customers as $index => $customer)
{
//dump($client);die();
fputcsv($handle,array(
$customer->getName(),
$customer->getAdress(),
$customer->getCity(),
$customer->getCode(),
),';');
}
fclose($handle);
});
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8', 'application/force-download');
$response->headers->set('Content-Disposition','attachment; filename='.$fileName);
return $response;
}
I call this function in my controler like this:
if (isset($_POST['export']))
{
$export = $exp->exportCsv($customers);
}
Have you any idea, please???
If you want to see what happened in your streamed response and what is the error, you just have to call the callback function outside the response.
$callback = function() use ($customers){
$handle = fopen('php://output', 'w+');
// Nom des colonnes du CSV
fputcsv($handle, array('Name',
'Adress',
'City',
'Code'
), ';');
//Champs
foreach ($customers as $index => $customer)
{
//dump($client);die();
fputcsv($handle,array(
$customer->getName(),
$customer->getAdress(),
$customer->getCity(),
$customer->getCode(),
),';');
}
fclose($handle);
};
$callback();exit;
And after just delete the last line and insert the callback function inside the StreamedResponse object $response->setCallback($callback);

why csv export not working?

I try to do a csv export on my symfony project and i think that something is wrong because the function return a simple response and don't download the csv.
here is the function:
public function exportCsv($customers)
{
$fileName = "export_" . date("d_m_Y") . ".csv";
$response = new StreamedResponse();
$handle = fopen('php://output', 'w+');
fputcsv($handle, array('Name',
'Adress',
'City',
'Code'
), ';');
foreach ($customers as $index => $custom)
{
fputcsv($handle,array(
$custom->getName(),
$custom->getAdress(),
$custom->getCity(),
$client->getCode(),
),';');
}
fclose($handle);
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition','attachment; filename='.$fileName);
return $response;
}
After creating a streamed response object, you needed to add the callback function that will fill out your response object with content: $response->setCallback().
public function exportCsv($customers)
{
$fileName = "export_" . date("d_m_Y") . ".csv";
$response = new StreamedResponse();
$response->setCallback(function() {
$handle = fopen('php://output', 'w+');
fputcsv($handle, array('Name', 'Adress', 'City', 'Code'),';');
foreach ($customers as $index => $custom)
{
fputcsv($handle,array(
$custom->getName(),
$custom->getAdress(),
$custom->getCity(),
$client->getCode(),
),';');
}
fclose($handle);
});
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition','attachment;
filename='.$fileName);
return $response;
}

How can i convert a yml,json or xml to csv

I'm using the bundle "JMSSerializerBundle" for export retrieved entity data. I can export the results as json, xml or yml successfully.
But i need also a csv export for this results. This bundle can't handle csv export. But i'm also not sure how can i convert json,xml or yml to csv, because csv is a flat file.
Have anyone solve this issue before?
Update
Now i create an solution for my problem, i'm partially satisfied with my solution, because it is not recursive. I will show it.
if ($format == 'csv') {
$json = $serializer->serialize($query, 'json', SerializationContext::create()->enableMaxDepthChecks());
return $this->toCsv(json_decode($json, true));
}
/**
* #todo write an recursive function for deeper levels
*
* #param $data
* #return array
*/
protected function toCsv($data)
{
$headers = array();
$outerCounter = 0;
foreach ($data as $key => $value) {
foreach ($value as $i => $j) {
if (!is_array($j)) {
$headers[] = $i;
$result[$outerCounter][$i] = $j;
} else {
foreach ($j as $k => $m) {
if (!is_array($m)) {
$headers[] = $i. '_'.$k;
$result[$outerCounter][$i. '_'.$k] = $m;
} else {
foreach ($m as $n => $l) {
if (!is_array($l)) {
$headers[] = $i.'_'.$k.'_'.$n;
$result[$outerCounter][$i.'_'.$k.'_'.$n] = $l;
}
}
}
}
}
}
$outerCounter++;
}
asort($headers);
$headers = array_unique($headers);
return array('headers' => $headers, 'data' => $result);
}

Change User Avatar Programmatically in Wordpress

Is it possible to change the user avatar in WordPress programmatically? I'm asking because I'm facing a problem right now in displaying the user avatar in WordPress multisite: the Avatar is not displaying.
I had to do three things to be able to programmatically insert user avatars into my WordPress starting with an avatar that is hosted at a remote URL.
Install the WP User Avatar plugin.
Borrow an upload function from WooCommerce. See below.
Adapt some code from a similar support post
Suppose you have a user whose avatar is $avatar_url = 'http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded&a';
I use the upload_product_image() from WooCommerce's class-wc-api-products.php to get the avatar into my local server.
Then, using some of the code from this support post, create an attachment.
Then associate the attachment with the user.
This works only with the WP User Avatar plugin.
function se13911452_set_avatar_url($avatar_url, $user_id) {
global $wpdb;
$file = upload_product_image($avatar_url);
$wp_filetype = wp_check_filetype($file['file']);
$attachment = array(
'guid' => $file['url'],
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($file['file'])),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $file['file']);
$attach_data = wp_generate_attachment_metadata($attach_id, $file['file']);
wp_update_attachment_metadata($attach_id, $attach_data);
update_user_meta($user_id, $wpdb->get_blog_prefix() . 'user_avatar', $attach_id);
}
From WooCommerce's class-wc-api-products.php
/**
* WooCommerce class-wc-api-products.php
* See https://github.com/justinshreve/woocommerce/blob/master/includes/api/class-wc-api-products.php
* Upload image from URL
*
* #since 2.2
* #param string $image_url
* #return int|WP_Error attachment id
*/
function upload_product_image($image_url) {
$file_name = basename(current(explode('?', $image_url)));
$wp_filetype = wp_check_filetype($file_name, null);
$parsed_url = #parse_url($image_url);
// Check parsed URL
if(!$parsed_url || !is_array($parsed_url)) {
throw new WC_API_Exception('woocommerce_api_invalid_product_image', sprintf(__('Invalid URL %s', 'woocommerce'), $image_url), 400);
}
// Ensure url is valid
$image_url = str_replace(' ', '%20', $image_url);
// Get the file
$response = wp_safe_remote_get($image_url, array(
'timeout' => 10
));
if(is_wp_error($response) || 200 !== wp_remote_retrieve_response_code($response)) {
throw new WC_API_Exception('woocommerce_api_invalid_remote_product_image', sprintf(__('Error getting remote image %s', 'woocommerce'), $image_url), 400);
}
// Ensure we have a file name and type
if(!$wp_filetype['type']) {
$headers = wp_remote_retrieve_headers($response);
if(isset($headers['content-disposition']) && strstr($headers['content-disposition'], 'filename=')) {
$disposition = end(explode('filename=', $headers['content-disposition']));
$disposition = sanitize_file_name($disposition);
$file_name = $disposition;
}
elseif(isset($headers['content-type']) && strstr($headers['content-type'], 'image/')) {
$file_name = 'image.' . str_replace('image/', '', $headers['content-type']);
}
unset($headers);
}
// Upload the file
$upload = wp_upload_bits($file_name, '', wp_remote_retrieve_body($response));
if($upload['error']) {
throw new WC_API_Exception('woocommerce_api_product_image_upload_error', $upload['error'], 400);
}
// Get filesize
$filesize = filesize($upload['file']);
if(0 == $filesize) {
#unlink($upload['file']);
unset($upload);
throw new WC_API_Exception('woocommerce_api_product_image_upload_file_error', __('Zero size file downloaded', 'woocommerce'), 400);
}
unset($response);
return $upload;
}
Most likely somewhere the get_avatar filter is being called and doing something. I recommend searching your plugins and themes for get_avatar and looking at things that look like: add_filter ('get_avatar', .....
Otherwise, you can write your own behavior with the code below.
<?php // in a plugin file or in a theme functions.php
function SO13911452_override_avatar ($avatar_html, $id_or_email, $size, $default, $alt) {
// check all values
return $avatar_html
}
add_filter ('get_avatar', 'SO13911452_override_avatar', 10, 5);
This will works :
add_filter('get_avatar_data', 'ht1_change_avatar', 100, 2);
function ht1_change_avatar($args, $id_or_email) {
if($id_or_email == 1) {
$args['url'] = 'https://uinames.com/api/photos/female/1.jpg';
}
if($id_or_email == 2) {
$args['url'] = 'https://uinames.com/api/photos/male/19.jpg';
}
return $args;
} // end of function
If you have avatar dir location metas for users, then use this for all users :
add_filter('get_avatar_data', 'ht1_change_avatar', 100, 2);
function ht1_change_avatar($args, $id_or_email) {
$avatar_url = get_user_meta($id_or_email, 'avatar', true);
$args['url'] = $avatar_url;
return $args;
} // end of function
Hope you get the point.
first add author_pic meta to user profile:
update_usermeta( $user_id, 'author_pic', trim($_POST['author_pic']) );
and add this filter to template function:
add_filter('get_avatar_data', 'ow_change_avatar', 100, 2);
function ow_change_avatar($args, $user_data) {
if(is_object($user_data)){
$user_id = $user_data->user_id;
} else{
$user_id = $user_data;
}
if($user_id){
$author_pic = get_user_meta($user_id, 'author_pic', true);
if($author_pic){
$args['url'] = $author_pic;
} else {
$args['url'] = 'registerd user default img url';
}
} else {
$args['url'] = 'guast user img url';
}
return $args;
}

Resources