How to get thumbnailPhoto from Active Directory ? php - php

I have this code :
if (TRUE === ldap_bind($ldap_connection, $ldap_username, $ldap_password)){
$ldap_base_dn = 'DC=xx,dc=xx,dc=xx';
$search_filter = '(&(objectCategory=person)(samaccountname=*))';
$attributes = array();
$attributes[] = 'givenname';
$attributes[] = 'mail';
$attributes[] = 'samaccountname';
$attributes[] = 'ipphone';
$attributes[] = 'thumbnailPhoto';
$result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter, $attributes);
if (FALSE !== $result){
$entries = ldap_get_entries($ldap_connection, $result);
for ($x=0; $x<$entries['count']; $x++){
if (!empty($entries[$x]['givenname'][0]) &&
!empty($entries[$x]['mail'][0]) &&
!empty($entries[$x]['samaccountname'][0]) &&
!empty($entries[$x]['ipphone'][0]) &&
'Shop' !== $entries[$x]['ipphone'][0] &&
'Account' !== $entries[$x]['ipphone'][0]){
$ad_users[strtoupper(trim($entries[$x]['samaccountname'][0]))] = array('email' => strtolower(trim($entries[$x]['mail'][0])),'first_name' => trim($entries[$x]['givenname'][0]),'phone' => trim($entries[$x]['ipphone'][0]), 'photo' => trim ($entries[$x]['thumbnailPhoto'][0]));
}
}
}
ldap_unbind($ldap_connection);
}
echo json_encode($ad_users);
I get only null for thumbnailPhoto .
How to handle this kind of data ? Can I get the url of this photo ?
I'm developing iOS app and sending employee data using json in php but how can I send this thumbnailPhoto also with each employee in json?

You have to use the attribute 'thumbnailphoto' and not 'thumbnailPhoto' (without capital letter).
Then in your $ad_users array you have to convert to base64 insted of trim :
'photo' => base64_encode ($entries[$x]['thumbnailPhoto'][0])

Related

How to repeat fuction in php?

Is it possible to repeat a function when it has finished. For Example: I have a function for export mysql to json file with a limit of 100 data. if it is successful create a json file with 100 data. Then it will repeat the same function to create json file 100 more data (no duplicate data) until the data runs out.
my code for generate json file :
$results = $db->SELECT()
->FROM( array( 'MM'=>'M_MEMBER'),
array( 'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS'
)
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT(100)
->QUERY()->FETCHALL();
if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
{
$counter = formatNbr($counterFile);
$data = array();
foreach ($results as $key=>$row) {
$data[$key] = $row;
$data[$key]['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$out = array_values($data);
$jsonAr = json_encode($out);
$json = substr($jsonAr, 1, -1);
$jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
$file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
$createJson = file_put_contents($file, $jsonData);
if($createJson){
echo "Create Json File Success In :".$file;
}else{
echo "Create Json Failed";
}
}
the code can only generate a json file once, how can it be repeated after generating a successful json file
note: I added a flag for each successful data generated json file
You can extract your codes to a function and use the function in the loop.
Example:
function exporter($limit = 100)
{
$results = $db->SELECT()
->FROM( array( 'MM'=>'M_MEMBER'),
array( 'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS'
)
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT($limit)
->QUERY()->FETCHALL();
if (!empty($results) && $results['SYNC_FLAG'] != 'Y')
{
$counter = formatNbr($counterFile);
$data = array();
foreach ($results as $key=>$row) {
$data[$key] = $row;
$data[$key]['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$out = array_values($data);
$jsonAr = json_encode($out);
$json = substr($jsonAr, 1, -1);
$jsonData = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json);
$file = $store_path_pos.'dataMember_'.date('Y-m-d').'_'.$counter.'.json';
$createJson = file_put_contents($file, $jsonData);
if($createJson) {
echo "Create Json File Success In :".$file;
} else {
echo "Create Json Failed";
}
}
$numberOfRows = 10000; # use the count query here
$limit = 100;
while($numberOfRows > 0) {
exporter($limit);
$numberOfRows -= $limit;
}
Also, you can call your function in your function recursively (https://www.w3schools.blog/php-recursive-functions)
Putting the existing code in a loop seems like the obvious answer here.
do {
$results = $db
->SELECT()
->FROM(
['MM'=>'M_MEMBER'],
[
'MEMBER_ID' => 'MM.MEMBER_ID',
'FIRST_NAME' => 'MM.FIRST_NAME',
'LAST_NAME' => 'MM.LAST_NAME',
'MEMBER_GROUP' => 'MM.MEMBER_GROUP',
'MEMBER_GROUP1' => 'MM.MEMBER_GROUP1',
'PHONE_NUMBER' => 'MM.PHONE_NUMBER',
'MEMBERSHIP' => 'MM.MEMBERSHIP',
'UPLOAD_DATE' => 'MM.UPLOAD_DATE',
'STATUS' => 'MM.STATUS',
]
)
->WHERE('DATE(MM.UPLOAD_DATE) = CURDATE()')
->WHERE('SYNC_FLAG = ?','N')
->LIMIT(100)
->QUERY()
->FETCHALL();
if (count($results) === 0) {
break;
}
$data = [];
foreach ($results as $row) {
$row['_id'] = (string) Application_Helper_General::generateIdJsonFile();
$data[] = $row;
//
// this is UNSAFE and inefficient, use a prepared statement if possible
//
$queryUdateMemberFlag = 'UPDATE M_MEMBER SET SYNC_FLAG = "Y" WHERE MEMBER_ID = '.$row['MEMBER_ID'].'';
$db->query($queryUdateMemberFlag);
}
$json = json_encode($out);
$filename = sprintf(
"%sdataMember_%s_%s.json",
$store_path_pos,
date("Y-m-d"),
formatNbr($counterFile)
);
if ($json && file_put_contents($filename, $json)) {
echo "Create Json File Success In $file";
} else {
echo "Create Json Failed";
}
} while (true);
I fixed a few inefficiencies in your code; I have no idea what DB library you're using but as a rule you should never inject variables into an SQL query. It's likely safe in this context, but if your library allows you should prepare the statement outside the loop and execute it inside the loop for better performance.

Laravel maatwebsite excel package import 2000+ rows results in 1390 code error

I have 4 excel files that contains 1000 rows in every file. I merged it and make it 4000 so that I can save some time. But if I import the merged file it returns me an error of General error: 1390 Prepared statement contains too many placeholders. But when I insert them ony by one it works. I dont know why it return such error, they have even the same values in every column. Can someone tell me what to do with this error? Help would be appriciated. Thanks a lot
Im using laravel maatwebsite excel package.
My import code
public function import(Request $request)
{
if($request->hasFile('template')){
$path = $request->file('template')->getRealPath();
$data = \Excel::load($path)->get();
if($data->count() > 0){
$rows = $data->toArray();
foreach ($rows as $row) {
$level = '';
$stack = '';
$unit = '';
$gunit = '';
$street = '';
$block_unit = '';
//DONT MIND THIS FUNCTION HERE
if (strpos($row['address'], '#') !== false) {
$unit = explode("#",$row['address']);
$gunit = $unit[1];
$block = explode(" ",$unit[0],2);
if(isset($unit[1])) {
$x = explode("-",$unit[1]);
$level = $x[0];
$stack = $x[1];
$street = $block[1];
$block_unit= $block[0];
}
}
elseif(strpos($row['address'], ' ') !== false){
$unit = explode(" ",$row['address']);
$block = explode(" ",$unit[0],2);
if(isset($unit[1])) {
$x = explode("-",$unit[1]);
$level = '';
$stack = '';
$x = preg_replace('/[0-9]+/', '', $row['address']);
$street = $x.substr($street,1);
$block_unit= $block[0];
}
}
else{
$level = '';
$stack = '';
$unit = '';
$gunit = '';
$block_unit = '';
$street = '';
}
//END
$inserts[]=[
'transtype' => 'RESI',
'project_name' => $row['project_name'],
'unitname' => $gunit,
'block' => $block_unit,
'street' => $street,
'level' => $level,
'stack' => $stack,
'no_of_units' => $row['no._of_units'],
'area' => $row['area_sqm'],
'type_of_area' => $row['type_of_area'],
'transacted_price' => $row['transacted_price'],
'nettprice' => $row['nett_price'],
'unitprice_psm' => $row['unit_price_psm'],
'unitprice_psf' => $row['unit_price_psf'],
'sale_date' => $row['sale_date'],
'contract_date' => $row['sale_date'],
'property_type' => $row['property_type'],
'tenure' => $row['tenure'],
'completion_date' => $row['completion_date'],
'type_of_sale' => $row['type_of_sale'],
'purchaser_address_indicator' => $row['purchaser_address_indicator'],
'postal_district' => $row['postal_district'],
'postal_sector' => $row['postal_sector'],
'postal_code' => $row['postal_code'],
'planning_region' => $row['planning_region'],
'planning_area' => $row['planning_area'],
];
}
}
if(empty($inserts)){
dd('Request data does not have any files to import.');
}
else {
\DB::table('xp_pn_ura_transactions')->insert($inserts);
dd('record inserted');
}
}
}
You can not insert more than 1000 records using laravel insert() method. If you want to achieve expected output then you can use array_chunk function of php or collection of laravel.
For example using array_chunk :
$chuncked = array_chunk($inserts, 1000);
foreach($chuncked as $insert){
\DB::table('xp_pn_ura_transactions')->insert($insert);
}

Imploding Delimiters True Position (PHP)?

It's a function in my class. I have no idea for imploding $newConditions with ( OR ) ( AND ).
Anybody have an idea ?
// #GETSSQ = Get Secured Select Query
function getSSQ($query) {
$conDelimiters = array(' OR ',' AND '); // Condition Delimiters
$fivaDelimiters = array('LIKE','<=>','<>','=>','<=','!=','=','<','>'); // Field & Value delimiters {Operators}
$conditions = preg_split("/(".implode('|',$conDelimiters).")/", $query);
$newConditions = array();
$operator = array("operator" => null);
foreach ($conditions as $idx => $cond) {
$operator["index"] = strlen($cond);
foreach ($fivaDelimiters as $sym) {
$pos = strpos($cond,$sym);
if ($pos === false)
continue;
else {
if ($pos < $operator['index']) {
$operator['index'] = $pos;
$operator['operator'] = $sym;
}
}
}
// Operatör bölme işlemine devam et...
$parts = array();
if ($operator['operator'] === null) {
$error = array(
"error" => "Koşullar arası yazım hatası tespit edildi. [".$this->options['connectionType'].":".$query."]",
"code" => "008"
);
$this->showError($error);
continue;
} else {
$condParts = explode($operator['operator'],$cond);
foreach ($condParts as $idx => $val) {
$condParts[$idx] = trim($val);
}
$parts['field'] = $this->__getSSQ_editFields($condParts[0]);
$parts['operator'] = $this->__getSSQ_editOperators($operator['operator']);
$newValue = $condParts[1];
if (count($condParts) > 2) { // If condition value has an operator character set
unset($condParts[0]);
$newValue = implode($operator['operator'],$condParts);
}
if (preg_match("/^['|\"](.*?)['|\"]$/", $newValue)) { // If value has {'} or {"} character begin & end , remove it
$newValue = substr($newValue, 1, (strlen($newValue)-2));
}
$newValue = $this->__getSSQ_editValues($newValue);
$parts['value'] = $newValue;
} #ENDIF OPERATOR === NULL
$newConditions[] = $parts['field'].' '.$parts['operator'].' '.$parts['value'];
} #END FOREACH CONDITIONS
var_dump($newConditions);
}
For Example My Function :
$condition = "id=5 AND parentCategory=2 AND firstName LIKE 'B%' AND usingMobile = 'true'";
$db = new XXClass();
$db->getSSQ($condition);
This output =>
array (size=4)
0 => string 'id = '5'' (length=8)
1 => string 'parentCategory = '2'' (length=20)
2 => string 'firstName LIKE 'B%'' (length=19)
3 => string 'usingMobile = 'true'' (length=20)
I can reach Fields , Operators , Values with __getSSQ_editXXXXX functions

Magento attributes import php gives internal server error

I've been looking for an extension or php of some sort to export and import my attributes. Because of website moving to another server, this is needed. I have a lot of attributes and I'm not willing to do it by hand.
I've seen this post and used the code:
Source: https://magento.stackexchange.com/questions/11520/how-to-export-and-import-all-attributes-and-attribute-sets-from-one-magento-to-o <- credits to this guy!
Code export attributes:
<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
Mage::app();
$entity_type_id = Mage::getModel('catalog/product')->getResource()->getTypeId();
prepareCollection($entity_type_id);
function prepareCollection($ent_type_id){
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_read');
$select_attribs = $connection->select()
->from(array('ea'=>$resource->getTableName('eav/attribute')))
->join(array('c_ea'=>$resource->getTableName('catalog/eav_attribute')), 'ea.attribute_id = c_ea.attribute_id');
// ->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
// ->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
$select_prod_attribs = $select_attribs->where('ea.entity_type_id = '.$ent_type_id)
->order('ea.attribute_id ASC');
$product_attributes = $connection->fetchAll($select_prod_attribs);
$select_attrib_option = $select_attribs
->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
->order('e_ao.attribute_id ASC');
$product_attribute_options = $connection->fetchAll($select_attrib_option);
$attributesCollection = mergeCollections($product_attributes, $product_attribute_options);
prepareCsv($attributesCollection);
}
function mergeCollections($product_attributes, $product_attribute_options){
foreach($product_attributes as $key => $_prodAttrib){
$values = array();
$attribId = $_prodAttrib['attribute_id'];
foreach($product_attribute_options as $pao){
if($pao['attribute_id'] == $attribId){
$values[] = $pao['value'];
}
}
if(count($values) > 0){
$values = implode(";", $values);
$product_attributes[$key]['_options'] = $values;
}
else{
$product_attributes[$key]['_options'] = "";
}
/*
temp
*/
$product_attributes[$key]['attribute_code'] = $product_attributes[$key]['attribute_code'];
}
return $product_attributes;
}
function prepareCsv($attributesCollection, $filename = "importAttrib.csv", $delimiter = '|', $enclosure = '"'){
$f = fopen('php://memory', 'w');
$first = true;
foreach ($attributesCollection as $line) {
if($first){
$titles = array();
foreach($line as $field => $val){
$titles[] = $field;
}
fputcsv($f, $titles, $delimiter, $enclosure);
$first = false;
}
fputcsv($f, $line, $delimiter, $enclosure);
}
fseek($f, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="'.$filename.'"');
fpassthru($f);
}
Code import attributes:
<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/../app/Mage.php';
Mage::app();
// $fileName = MAGENTO . '/var/import/importAttrib.csv';
$fileName = 'importAttrib.csv';
// getCsv($fileName);
getAttributeCsv($fileName);
function getAttributeCsv($fileName){
// $csv = array_map("str_getcsv", file($fileName,FILE_SKIP_EMPTY_LINES));
$file = fopen($fileName,"r");
while(!feof($file)){
$csv[] = fgetcsv($file, 0, '|');
}
$keys = array_shift($csv);
foreach ($csv as $i=>$row) {
$csv[$i] = array_combine($keys, $row);
}
foreach($csv as $row){
$labelText = $row['frontend_label'];
$attributeCode = $row['attribute_code'];
if($row['_options'] != "")
$options = explode(";", $row['_options']); // add this to createAttribute parameters and call "addAttributeValue" function.
else
$options = -1;
if($row['apply_to'] != "")
$productTypes = explode(",", $row['apply_to']);
else
$productTypes = -1;
unset($row['frontend_label'], $row['attribute_code'], $row['_options'], $row['apply_to'], $row['attribute_id'], $row['entity_type_id'], $row['search_weight']);
createAttribute($labelText, $attributeCode, $row, $productTypes, -1, $options);
}
}
/**
* Create an attribute.
*
* For reference, see Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
*
* #return int|false
*/
function createAttribute($labelText, $attributeCode, $values = -1, $productTypes = -1, $setInfo = -1, $options = -1)
{
$labelText = trim($labelText);
$attributeCode = trim($attributeCode);
if($labelText == '' || $attributeCode == '')
{
echo "Can't import the attribute with an empty label or code. LABEL= [$labelText] CODE= [$attributeCode]"."<br/>";
return false;
}
if($values === -1)
$values = array();
if($productTypes === -1)
$productTypes = array();
if($setInfo !== -1 && (isset($setInfo['SetID']) == false || isset($setInfo['GroupID']) == false))
{
echo "Please provide both the set-ID and the group-ID of the attribute-set if you'd like to subscribe to one."."<br/>";
return false;
}
echo "Creating attribute [$labelText] with code [$attributeCode]."."<br/>";
//>>>> Build the data structure that will define the attribute. See
// Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
$data = array(
'is_global' => '0',
'frontend_input' => 'text',
'default_value_text' => '',
'default_value_yesno' => '0',
'default_value_date' => '',
'default_value_textarea' => '',
'is_unique' => '0',
'is_required' => '0',
'frontend_class' => '',
'is_searchable' => '1',
'is_visible_in_advanced_search' => '1',
'is_comparable' => '1',
'is_used_for_promo_rules' => '0',
'is_html_allowed_on_front' => '1',
'is_visible_on_front' => '0',
'used_in_product_listing' => '0',
'used_for_sort_by' => '0',
'is_configurable' => '0',
'is_filterable' => '0',
'is_filterable_in_search' => '0',
'backend_type' => 'varchar',
'default_value' => '',
'is_user_defined' => '0',
'is_visible' => '1',
'is_used_for_price_rules' => '0',
'position' => '0',
'is_wysiwyg_enabled' => '0',
'backend_model' => '',
'attribute_model' => '',
'backend_table' => '',
'frontend_model' => '',
'source_model' => '',
'note' => '',
'frontend_input_renderer' => '',
);
// Now, overlay the incoming values on to the defaults.
foreach($values as $key => $newValue)
if(isset($data[$key]) == false)
{
echo "Attribute feature [$key] is not valid."."<br/>";
return false;
}
else
$data[$key] = $newValue;
// Valid product types: simple, grouped, configurable, virtual, bundle, downloadable, giftcard
$data['apply_to'] = $productTypes;
$data['attribute_code'] = $attributeCode;
$data['frontend_label'] = array(
0 => $labelText,
1 => '',
3 => '',
2 => '',
4 => '',
);
//<<<<
//>>>> Build the model.
$model = Mage::getModel('catalog/resource_eav_attribute');
$model->addData($data);
if($setInfo !== -1)
{
$model->setAttributeSetId($setInfo['SetID']);
$model->setAttributeGroupId($setInfo['GroupID']);
}
$entityTypeID = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
$model->setEntityTypeId($entityTypeID);
$model->setIsUserDefined(1);
//<<<<
// Save.
try
{
$model->save();
}
catch(Exception $ex)
{
echo "Attribute [$labelText] could not be saved: " . $ex->getMessage()."<br/>";
return false;
}
if(is_array($options)){
foreach($options as $_opt){
addAttributeValue($attributeCode, $_opt);
}
}
$id = $model->getId();
echo "Attribute [$labelText] has been saved as ID ($id).<br/>";
// return $id;
}
function addAttributeValue($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
if(!attributeValueExists($arg_attribute, $arg_value))
{
$value['option'] = array($arg_value,$arg_value);
$result = array('value' => $value);
$attribute->setData('option',$result);
$attribute->save();
}
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
function attributeValueExists($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
The import code doesn't work. It returns a 500 Internal Server error. Is there anything I miss in the import code? And if not, do you have a suggestion for me?
If any more information needed, feel free to ask.
Thanks in advance!
How long does it take until the 500 appears?
If your PHP runs under CGI and the activityTimeout is below the max_execution_time (e.g. you set max_execution_time to 1200 via ini_set or htaccess and CGIs activityTimeout is just 40 by default) it will throw a 500 instead of a PHP-error. It allways acts like that if CGIs settings are lower tha the PHP ones (memory, maxrequests, timeout, etc.)
A real misconfiguration 500 (e.g. php.ini or .htaccess) would appear just in time on startup, not only when yous script starts/runs.

How to explode csv string (not csv file) safely into a usable php array

I am using wordpress and need to dynamically populate a dropdpown. How ever I am having issues with fopen php function in wordpress. https://stackoverflow.com/questions/21990467/
So I've given up trying to import csv file and resorted to just placing my csv file contents into an wordpress options field for a quick fix.
But I am struggling with exploding the csv string safely to then use specific columns for choice label and values.
Can any please advise on how I can do this?
Thank you in advance.
The function
// rider nationality
function motocom_rider_nationality( $field )
{
// reset choices
$field['choices'] = array();
// get the textarea value from options page without any formatting
$choices = get_field('nationality_codes', 'option', false);
// explode the value so that each line is a new array piece
$choices = explode(",", $choices);
// remove any unwanted white space
$choices = array_map('trim', $choices);
$field['choices'] = array(
null => 'Select nationality...'
);
// loop through array and add to field 'choices'
if( is_array($choices) )
{
foreach( $choices as $choice )
{
$label = $choice['Country'];
$value = $choice['A4'];
$field['choices'][ $value ] = $label;
}
}
// Important: return the field
return $field;
}
add_filter('acf/load_field/name=rider_nationality', 'motocom_rider_nationality');
The csv string in the options textarea field...
Country,A2,A3,Number
Aaland Islands,AX,ALA,248
Afghanistan,AF,AFG,4
Albania,AL,ALB,8
Algeria,DZ,DZA,12
Samoa,AS,ASM,16
Andorra,AD,AND,20
Fixed it using this solution...
// csv to array
function motocom_csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
// rider nationality
function motocom_rider_nationality( $field )
{
// reset choices
$field['choices'] = array();
// get the textarea value from options page without any formatting
$choices = motocom_csv_to_array( get_template_directory() . '/csv/nationality-codes.csv' );
$field['choices'] = array(
null => 'Select nationality...'
);
// loop through array and add to field 'choices'
if( is_array($choices) )
{
foreach( $choices as $choice )
{
$label = $choice['Country'];
$value = $choice['A3'];
$field['choices'][ $value ] = $label . ' [' . $value . ']';
}
}
// Important: return the field
return $field;
}
add_filter('acf/load_field/name=rider_nationality', 'motocom_rider_nationality');

Categories