I'm trying to send test message with my PHP SOAP client. I'm using BeSimpleSoap library because I had problems with standard PHP SOAP calss and NuSOAP class. This is my script:
<?php
function __autoload($class_name) {
include "C:\\xampp\\htdocs\\NIAS\\BeSimpleSoap-master\\src\\" .$class_name . '.php';
}
$full_path="C:\\xampp\\htdocs\\NIAS\\Unload\\";
$destination="C:\\xampp\\htdocs\\NIAS\\Arhiva\\";
$OIB_URL="https://demo.apis-it.hr:8444/kpoib/kp_lista_aktiviranih_korisnika.txt";
//$OIB_list=file_get_contents($OIB_URL);
//echo $OIB_list;
$date_time = date("Y-m-d") . "T" . date("G") . ":" . date("i") . ":" . date("s");
$rows_lines="";
$input_file=scandir($full_path);
foreach ($input_file as $input_name){
if($input_name=="." || $input_name=="..")
continue;
$lines = file($full_path . $input_name);
//$flag=true; //flag for skiping lead row in file
foreach($lines as $line)
{
//if($flag) { $flag = false; continue; }//skip the first row in file
$line_row = explode(':', $line);
//$rows_lines .= implode(";",$line_row);
if(substr($input_name,0,7)=="naknade"){
if(empty($line_row[6])){
$IBAN_tmp=$line_row[7].$line_row[8].'172700';
$IBAN=IBAN_generator($IBAN_tmp);
}
else{
$IBAN=$line_row[6];
}
$compensation = number_format($line_row[2],2);
$title="Obavijest o uplati naknade plaće zbog privremene nesposobnosti za rad, rodiljne i roditeljske potpore";
echo $rows_lines ="Poštovana/i,\nNa Vaš račun " . $IBAN . " upućena je " . $line_row[5] . " u iznosu od " . $compensation . " kuna za " . $line_row[0] . ". mjesec " . $line_row[1] . ". godine." . "</br>";
}
else if(substr($input_name,0,9)=="za_e_grad"){
$title="Obavijest o isteku dopunskog osiguranja";
echo $rows_lines ="Poštovana/i,\nVaše dopunsko zdravstveno osiguranje, broj iskaznice " . $line_row[1] . ", ističe " . $line_row[2] . " godine.". "</br>";
}
/*
$par_data = new StdClass();
$par_data->encoding = "EMBEDDED";
$par_data->any = $par_data;
*/
$par_data=array("KorisnickiPretinacPoruka" =>
array("Zaglavlje"=>
array("IdPosiljatelja"=>"000000001","IdPoruke"=>"833362f-063f-11e2-892e-0802200c9a62","DatumVrijemeSlanja"=>$date_time,"RazinaSigurnosti"=>2),
"Poruka" =>array("PinPrimatelja"=>"012345678901","OznakaDrzave"=>"HR","Predmet"=>$title,"Sadrzaj"=>$rows_lines)));
$par_envelope=array( "GsbEnvelope" =>
array( "MessageHeader" =>
array("SenderId" => "000000001",
"ServiceId" => "000000002",
"MessageId" => "833362f-063f-11e2-892e-0802200c9a62",
"SenderTimeStamp" => $date_time),
"Content" => array("MimeType" =>"application/xml","Data" =>array("encoding"=>"EMBEDDED","any"=>$par_data))));
$client = new BeSimple\SoapClient\SoapClient("GSBService.wsdl", array(
"trace"=>1,
"exceptions"=>1,
"local_cert" =>"C:\\PKI\\democacert.cer",
"passphrase"=>"",
"connection_timeout" => 300));
print_r( $client->sendMessage($par_envelope));
echo "<p>Request :".htmlspecialchars($client->__getLastRequest()) ."</p>";
echo "<p>Response:".htmlspecialchars($client->__getLastResponse())."</p>";
echo "<p>Debug:".soapDebug($client)."</p>";
}
if (copy($full_path.$input_name, $destination.$input_name)) {
$delete1[] = $full_path.$input_name;
}
}
if (!empty($delete1)){
foreach ($delete1 as $file1) {
unlink($file1);
}
}
function IBAN_generator($acc){
if(strlen($acc)!=23)
return;
$temp_str=substr($acc,0,3);
$remainder =$temp_str % 97;
for($i=3;$i<=22;$i++)
{
$remainder =$remainder .substr($acc,$i,1);
$remainder = $remainder % 97;
}
$con_num = 98 - $remainder;
if ($con_num<10)
{
$con_num="0".$con_num;
}
$IBAN="HR".$con_num.substr($acc,0,17);
return $IBAN;
}
?>
I have enabled extension=php_openssl.dll in php.ini.
I'm getting this error:
Warning: DOMDocument::save(/tmp\wsdl_9429a1dff02ce405ba48d1992f82604d.cache): failed to open stream: No such file or directory in C:\xampp\htdocs\NIAS\BeSimpleSoap-master\src\BeSimple\SoapClient\WsdlDownloader.php on line 204
Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn't load from '/tmp\wsdl_9429a1dff02ce405ba48d1992f82604d.cache' : failed to load external entity "/tmp/wsdl_9429a1dff02ce405ba48d1992f82604d.cache" in C:\xampp\htdocs\NIAS\BeSimpleSoap-master\src\BeSimple\SoapClient\SoapClient.php:113 Stack trace: #0 C:\xampp\htdocs\NIAS\BeSimpleSoap-master\src\BeSimple\SoapClient\SoapClient.php(113): SoapClient->SoapClient('/tmp\wsdl_9429a...', Array) #1 C:\xampp\htdocs\NIAS\HZZO-OKP-SOAP.php(76): BeSimple\SoapClient\SoapClient->__construct('GSBService.wsdl', Array) #2 {main} thrown in C:\xampp\htdocs\NIAS\BeSimpleSoap-master\src\BeSimple\SoapClient\SoapClient.php on line 113
(This was solved rather tersely in the comments, transcribed herein. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
I have solved it by editing PHP.ini with soap.wsdl_cache_dir="C:\xampp\htdocs\NIAS\tmp"
Related
Line 83 of the error I get and put below is from the UssdNode.php
file which contains the declaration of the variable $item=$items[$i]
in the recurseMenu method below.
Line 45 of the same error in the UssdTree.php file contains the
declaration of the variable $node=$this->treeMenu[$name]; in the
getNode method below.
Line 94 of the same error in the UssdNode.php file contains the
declaration of the variable $title=$node->getTitle(); in the
recurseMenu method below.
My method or function recurseMenu (in: UssdNode.php) normally contains the list of menus (WHICH I LOOK TO DISPLAY) contained in the variable $title=$node->getTitle():
function recurseMenu($items,$bufferLimit) {
$objectString="<strong>". $this->getTitle() . "</strong>" . PHP_EOL;
$lastMenu=false;
if(count($items)>0) {
for($i=$this->index;$i<$bufferLimit;$i++){
$item=$items[$i];
/* echo "<pre>";
print_r($item);
echo "</pre>"; */
$num=$i+1;
//get node by name
$userSessions=$_SESSION['userSessions'];
$currUserSession=$userSessions[$this->address];
$node=$currUserSession->getNode($item);
$title=$node->getTitle();
$objectString=$objectString . PHP_EOL .$num . '. ' .$title;
}
} else {
$objectString=$objectString.PHP_EOL . 'NO DATA AVAILABLE, TRY AGAIN LATER';
}
$lastMenu=$bufferLimit==count($items);
$objectString=$objectString . PHP_EOL . PHP_EOL . "<strong>0. Exit</strong>";
if($this->getParent() != '0'){
$objectString=$objectString . PHP_EOL . "<strong>#. Back</strong>";
}
if($lastMenu===false){
$rem=count($items)-$this->index;
$objectString=$objectString . PHP_EOL . "<strong>99. Next (".$rem.")</strong>";
}
return $objectString;
}
The getNode method of the UssdTree.php file:
function getNode($name){
$node=$this->treeMenu[$name];
return $node;
}
And when I try the debug of $this->recurseMenu($items,$bufferLimit) in my toString method or function which displays the list of $title as strings:
function toString(){
$objectString='';
$items=$this->children;
$bufferLimit=(count($items)==0)?1:$this->getBufferLimit()+1;
echo "<pre>";
print_r($this->recurseMenu($items,$bufferLimit));
echo "</pre>";
do{
$bufferLimit-=1;
$objectString=$this->recurseMenu($items,$bufferLimit);
}while(strlen($objectString>160));
$this->index=$bufferLimit;
return $objectString;
}
The problem is that nothing is displayed. And I get the following error:
Notice: Undefined offset: 3 in
C:\laragon\www\ussd\ussdmenu-server-php\UssdNode.php on line 83
Notice: Undefined index: in
C:\laragon\www\ussd\ussdmenu-server-php\UssdTree.php on line 45
Fatal error: Uncaught Error: Call to a member function getTitle() on
null in C:\laragon\www\ussd\ussdmenu-server-php\UssdNode.php:94
Stack trace:
#0 C:\laragon\www\ussd\ussdmenu-server-php\UssdNode.php(59): UssdNode->recurseMenu(Array, 4)
#1 C:\laragon\www\ussd\ussdmenu-server-php\UssdUserSession.php(77): UssdNode->toString()
#2 C:\laragon\www\ussd\ussdmenu-server-php\UssdReceiver.php(51): UssdUserSession->fetchDisplay()
#3 C:\laragon\www\ussd\ussdmenu-server-php\UssdReceiver.php(43): UssdReceiver->handleChildBearingNode('paybill', '0772247408',
'1234567')
#4 C:\laragon\www\ussd\ussdmenu-server-php\UssdReceiver.php(15): UssdReceiver->handleContinuingRequests('0772247408', '4', '1234567')
#5 C:\laragon\www\ussd\receiver.php(28): UssdReceiver->onMessage(Array)
#6 C:\laragon\www\ussd\receiver.php(36): MyUssdReceiver::process(Array)
#7 {main} thrown in C:\laragon\www\ussd\ussdmenu-server-php\UssdNode.php on line 94
URL : http://localhost/ussd/receiver.php MSISDN :
How to correctly display the list of menus represented by the variable $title=$node->getTitle(); in the recurseMenu method below ?
Help me fix this error.
Just check for the index before accessing it?
for ($i = $this->index; $i < $bufferLimit; $i++) {
if (isset($items[$i])){
$item = $items[$i];
$num = $i + 1;
// get node by name
$userSessions = $_SESSION['userSessions'];
$currUserSession = $userSessions[$this->address];
$node = $currUserSession->getNode($item);
$title = $node->getTitle();
$objectString .= PHP_EOL . $num . '. ' . $title;
}
}
Or loop the items and check if there's more than the buffer or not
foreach ($items as $i => $item) {
if ($i >= $bufferLimit) {
break;
}
$num = $i + 1;
// get node by name
$userSessions = $_SESSION['userSessions'];
$currUserSession = $userSessions[$this->address];
$node = $currUserSession->getNode($item);
$title = $node->getTitle();
$objectString .= PHP_EOL . $num . '. ' . $title;
}
You're trying to access a key that doesn't exist. If your items array has 3 entries and the buffer limit is something like 10, you'll get errors starting from number 3 because they don't exist in the array.
This question already has answers here:
Illegal string offset Warning PHP
(17 answers)
Closed 9 months ago.
I get following error:
PHP message: PHP Fatal error: Uncaught TypeError: Cannot access offset of type string on string
on this line:
if ($uploadZoneData[1]['size'] != 0) {
On php 7.4 i had any troube but with php 8 i have.
What can be the problem?
EDIT: Full code of the related functions:
function uploadSingleFile($zoneImage, $fileMoveTo, $fileAllowedExtensions, $fileAllowedSize, $zoneCustomer, $zone)
{
global $config;
// define file upload settings
$errors = array();
$fileName = $zoneImage['name'];
$fileSize = $zoneImage['size'];
$fileTmp = $zoneImage['tmp_name'];
$fileType = $zoneImage['type'];
$fileExt = strtolower(end(explode('.', $zoneImage['name'])));
$MBtoByte = $fileAllowedSize * 1048576;
$extensions= $fileAllowedExtensions;
// define errors
if (in_array($fileExt, $extensions) === false) {
$errors[] = "Dieser Datei-Typ ist nicht erlaubt";
}
if ($fileSize > $MBtoByte) {
$errors[] = 'Die Datei ist zu gross';
}
// finally try to upload the file
if (empty($errors) == true) {
$temp = explode(".", $zoneImage["name"]);
$newfilename = $zoneCustomer . '-' . strtoupper($zone) . '-' . uniqid() . '.' . end($temp);
move_uploaded_file($fileTmp, $_SERVER["DOCUMENT_ROOT"] . $fileMoveTo . $newfilename);
$status = '1';
} else {
$status = '0';
}
// build array of the different outputs
$uploadStatus = array($status, $newfilename, $errors);
return $uploadStatus;
}
function updateZoneData($zoneFile, $zoneCustomer, $zone, $zoneLink, $maxWidth, $bannerID)
{
global $db;
// get customer values
$getCustomerValues = getColumnValue('customers', "WHERE `customerNr` = '" . $zoneCustomer . "'");
// define redirect url
switch ($zone) {
case "a1":
$redirectZone = "zones.php#zones-overview-a1-overview";
break;
case "a2":
$redirectZone = "zones.php#zones-overview-a2-overview";
break;
case "b1":
$redirectZone = "zones.php#zones-overview-b1-overview";
break;
case "b2":
$redirectZone = "zones.php#zones-overview-b2-overview";
break;
case "b3":
$redirectZone = "zones.php#zones-overview-b3-overview";
break;
case "b4":
$redirectZone = "zones.php#zones-overview-b4-overview";
break;
case "a9":
$redirectZone = "zones.php#zones-overview-a9-overview";
break;
case "a9-1":
$redirectZone = "zones.php#zones-overview-a9-1-overview";
break;
case "a11":
$redirectZone = "zones.php#zones-overview-a11-overview";
break;
default:
$redirectZone = "zones.php";
}
// upload file to the server
$uploadZoneData = uploadSingleFile($zoneFile, '/adserver/banners/', array("jpg", "jpeg", "png", "gif"), '3', $zoneCustomer, $zone);
if ($uploadZoneData[1]['size'] != 0) {
if ($uploadZoneData[0] == '1') {
// create ZIP-Backup (zone-banners) from '/adserver/banners' to '/cp/includes/files/zip-backups'
createZipBackup('/adserver/banners', '/cp/includes/files/zip-backups', 'adserver-banners.zip');
// get zone values & delete old bannerImg from file-system
$getZoneDeleteValues = getColumnValue('zones', "WHERE `customerNr` = '" . $zoneCustomer . "' AND `zone` = '" . $zone . "' AND `id` = '" . $bannerID . "'");
unlink($_SERVER["DOCUMENT_ROOT"] . '/adserver/banners/' . $getZoneDeleteValues['0']['bannerImg']);
// execute action
$updateZoneData = $db->update("zones", [
"customerNr" => $zoneCustomer,
"customer" => $getCustomerValues['0']['customer'],
"zone" => $zone,
"bannerImg" => $uploadZoneData[1],
"bannerLink" => $zoneLink,
"maxWidth" => $maxWidth,
"changeDate" => date("Y-m-d H:i:s")
], [
"id" => $bannerID
]);
redirectTo($redirectZone, 1, "« " . strtoupper($zone) . "-Banner (" . $getCustomerValues['0']['customer'] . " [K. N°: " . $zoneCustomer . "]) » wurde erfolgreich aktualisiert.", 'ZONES');
} else {
// collect and save errors (file-upload)
$collectedErrors = array_flatten($uploadZoneData[2]);
setcookie("collectedErrors", '1', time() + (1 * 5), "/"); // expire in 5 seconds
$_SESSION["collectedErrors"] = $collectedErrors;
redirectTo($redirectZone, 0, "« " . strtoupper($zone) . "-Banner (" . $getCustomerValues['0']['customer'] . " [K. N°: " . $zoneCustomer . "]) » konnte nicht aktualisiert werden.", 'ZONES');
}
} else {
// execute action
$updateZoneData = $db->update("zones", [
"customerNr" => $zoneCustomer,
"customer" => $getCustomerValues['0']['customer'],
"zone" => $zone,
"bannerLink" => $zoneLink,
"maxWidth" => $maxWidth,
"changeDate" => date("Y-m-d H:i:s")
], [
"id" => $bannerID
]);
redirectTo($redirectZone, 1, "« " . strtoupper($zone) . "-Banner (" . $getCustomerValues['0']['customer'] . " [K. N°: " . $zoneCustomer . "]) » wurde erfolgreich aktualisiert.", 'ZONES');
}
}
First of all, welcome to Stack Overflow!
This error means that you are trying to access the index [1]['size'] of the string, which is not valid. Be sure to check that uploadSingleFile(...) is returning you an array and not a string.
I checked your code and I saw that the returned array of uploadSingleFile have these three items:
$uploadStatus = array($status, $newfilename, $errors);
$newfilename is not an array. It is a string, as you defined here:
$newfilename = $zoneCustomer . '-' . strtoupper($zone) . '-' . uniqid() . '.' . end($temp);
Thanks for your answers the solution to my problem is.
Replace this
if ($uploadZoneData[1]['size'] != 0) {
with the following:
if (!empty($uploadZoneData[1])) {
I'm not a techie, so I find myself on StackOverflow quite often looking for answers. I had this problem and came here in search of an answer. I had already defined the array ($CA = []; in my case), but it was failing on levels deeper than 1 into the array. At its deepest, my array would look like this:
$CA[$row[2]][$row[3]][$row[4]][$row[5]]
The simplest way I can find to put this answer is that EVERY level of the array must be defined, so I ended up with this for each loop through my dataset: (Note: If $row[x] is not null, all $row[any number less than x] won't be null.)
WHILE ($row = $result->fetch_row()) {
if ( !is_null($row[2]) && !is_array($CA[$row[2]]) ) { $CA[$row[2]] = []; }
if ( !is_null($row[3]) && !is_array($CA[$row[2]][$row[3]]) ) { $CA[$row[2]][$row[3]] = []; }
if ( !is_null($row[4]) && !is_array($CA[$row[2]][$row[3]][$row[4]]) ) { $CA[$row[2]][$row[3]][$row[4]] = []; }
if ( !is_null($row[5]) && !is_array($CA[$row[2]][$row[3]][$row[4]][$row[5]]) ) { $CA[$row[2]][$row[3]][$row[4]][$row[5]] = []; }
... Code to set the array elements below ...
PHP no longer automatically creates the array depth you need; you must set it explicitly to avoid the error. Hope this makes it clearer for other non-techies on this page. I'm interested in any better ways to do it (I like to keep my code concise!)
you can use
if(isset(...))
that is an usual PHP 8 error
You should have to upgrade your php. This will help you. Because many codes doesn't work on old versions. SO upgrade PHP it will help.
else share your full code. we will try to resolve your error as soon as possible.
I'm writing a custom import script for SuiteCRM and I'm getting the error:
Warning: array_combine() expects parameter 2 to be array, boolean
given in /var/www/html/afscmedbv5test/custom/wimporter/newimporter.php
on line 162
My Script is as follows:
<?php
if (!defined('sugarEntry') || !sugarEntry) die ('Not a Valid Entry Point!');
$date = new DateTime();
echo '<H2>Wilderness Import Started</h2>';
echo $date->format('r').'<br>';
echo '-----------------------------------------------------------------------
--------------------------------------------------------------<br>';
require_once("include/utils/sugar_file_utils.php");
WildernessImportJob();
die();
function var_dump_ret($mixed = null) {
ob_start();
var_dump($mixed);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
function time_elapsed()
{
static $first = null;
static $previous = null;
$now = microtime(true);
if ($first == null) $first = $now;
if ($previous != null)
echo '--- Partial ' . round(($now - $previous), 2) . ', Total ' . round(($now
- $first), 2) . ' ---'; // 109s
$ret = round(($now - $previous), 2);
$previous = $now;
return $ret;
}
function myLog ($str2log)
{
file_put_contents('./zlog_'.date("j.n.Y").'.txt', date("H:i:s", time())."
".$str2log.PHP_EOL, FILE_APPEND);
}
function calcDelta($a1, $a2)
{
//combine into a nice associative array:
$delta=Array();
foreach ($a1 as $key=>$value)
{
if ($a1[$key] != $a2->$key)
$delta[] = array($key => ("Was ". $a1[$key]. ", became " . $a2->$key));
}
$num = count($data);
if (empty($a1)) $delta[] = array("a1" => ("Was empty"));
if (empty($a2)) $delta[] = array("a2" => ("Was empty"));
return $delta;
}
require_once("include/utils/sugar_file_utils.php");
function fillPerson($record, &$person)
{
// $record is what is being imported from CSV
// $person is the bean about to be filled and going into the SuitCRM DB. It
may be new or not, depending on whether it exists in the DB previously.
// name: only updates if not existant yet, because it's the key we use for
search, and because names are more complex with parts
if ($person->full_name_c == "") {
$recordname = $record["FULL NAME"]; // != "") ? $record["FULL NAME"] : "
[To-be-filled]");
//echo $prefix;
$recordname = str_replace(" ", " ", $recordname);
echo $recordname;
$parts = explode(" ", $recordname);
$person->last_name = array_pop($parts);
$person->first_name = $parts[0];
$person->name = $person->first_name . " " . $person->last_name;
$person->full_name_c = $record["FULL NAME"]; // custom field created in
Studio
}
//$datanasc = DateTime::createFromFormat('!m/d/Y', $record["PPE"]);
// $datasnasc->setTime(0, 0);
// $person->ppe_date_c = ($datanasc == false) ? "" : $datanasc->format('m-d-
Y');
//$person->ppe_date_c = $record["PPE"];
//print_r($person);
var_dump($person);
}
// finish by making a complete analysis of what changed:
return calcDelta($person->fetched_row, $person);
function GetOrCreateMember ($the_name)
{
//Check if the fullname is null
if ($the_name != "")
{
$person = BeanFactory::getBean("locte_Members");
$person = $person->retrieve_by_string_fields(array('full_name_c' =>
$the_name));
if (is_null($person))
{
//get members bean
$person = BeanFactory::newBean("locte_Members");
//set full_name_c to the_name variable
$person->full_name_c = $the_name;
// $person->lcl_employee_id = $personEmployeeID;
$person_name = str_replace(" ", " ", $the_name);
$parts = explode(" ", $person_name);
$person->last_name = array_pop($parts);
$person->first_name = $parts[0];
//combine first and last name to populate the fullname field
$person->name = $person->first_name . " " . $person->last_name;
$person_id = $person->save();
// add new duespayment to member record
// $rosterDuesPayments = BeanFactory::getBean('Dues Payments')-
>retrieve_by_string_fields(array('name'=> $duesEmployeeID));
// $person->load_relationship('locte_Members_adues_dues'); //confirm
relationship name in cache
// $person->dues_payments->add($rosterDuesPayments->id);
}
return $person;
}
return null;
}
function WildernessImportJob()
{
try
{
time_elapsed();
$GLOBALS['log']->info('Wilderness Import');
$config = new Configurator();
$config->loadConfig();
$xmlDataDir = 'custom/wimporter/ToImport'; //$config->config['WildernessImporter_DataFilePath'];
$GLOBALS['log']->info("Wilderness Import: Scanning XML Data dir $xmlDataDir...");
echo("<h3>Wilderness Import: Scanning XML Data dir $xmlDataDir...<br /></h3>");
$directoryContent = scandir($xmlDataDir);
$GLOBALS['log']->info("Wilderness Import: Scanning XML Data dir $xmlDataDir... [Found " . count($directoryContent) . " files]");
echo("<h3>Wilderness Import: Scanning XML Data dir $xmlDataDir... [Found " . count($directoryContent) . " files]</h3><br />");
foreach ($directoryContent as $itemFile)
{
if (is_dir($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile)) continue;
if (strcasecmp(substr($itemFile, -4), ".csv") != 0) continue;
$GLOBALS['log']->info("Wilderness Import: Processing $itemFile file...");
myLog("---------------------------------------------------");
myLog("Wilderness Import: Processing $itemFile file...");
myLog("----------------------------------------------------");
echo("<h4>---------------------------------------------------------------</h4>");
echo("<h4>Wilderness Import: Processing $itemFile file...</h4>");
echo("<h4>---------------------------------------------------------------</h4>");
$oFile = fopen($xmlDataDir . DIRECTORY_SEPARATOR . $itemFile, 'r');
if ($oFile !== FALSE)
{
// read entire file at once:
// expected separator is ",", expected encoding is UTF-8 without BOM (BOM is 3 weird characters in beginning of file)
while (($data[] = fgetcsv($oFile, 0, ',')) !== FALSE) { }
echo('File opened..... <br /> <br />');
fclose($oFile);
//combine into a nice associative array:
$arow=Array();
echo('Building CSV File Row Array <br /><br />');
$fields = array_shift($data);
echo('Building CSV Header Fields Array as shown below:<strong> <br /><br />');
echo implode(", ", $fields) . "</strong><br /><br />\n";
foreach ($data as $i=>$arow)
{
$GLOBALS['log']->info("Wilderness Import: array_combine " . $i);
$data[$i] = array_combine($fields, $arow);
}
unset($arow); // **********************************************! ! ! !! ! ! ! ! ! !! !
$num = count($data);
echo('Build Full Array of Roster to be Imported Complete. Entries to be imported are shown below <br /><br />');
for ($row=0; $row < $num - 1 ; $row++)
{ // normal bounds: from 0 to $num
//$num is the number of lines including header in csv file
echo "<strong>Filename: $itemFile | Roster Import, Row" . ($row + 1) . ":</strong><br />\n";
$GLOBALS['log']->info("Wilderness Import: Importing " . $data[$row]["FULL NAME"]);
// echo("<strong>Importing Roster Row #: ". ($row + 1) . "<br />" . "Local Number " . $data[$row]["AFFILIATE"] . "<br />" . "Employee: " . $data[$row]["FULL NAME"] . "</strong><br /><br />");
echo "<strong><table>\n";
foreach ($fields as $field) {
//echo "<tr><td>" . $field . "</td><td>" . $data[$row][$field] . "</td><td>" . $data[$row+1][$field] . "</td><td>" . $data[$row+2][$field] . "</td></tr>\n";
}
echo "</table>\n";
echo "File Row Data: ";
echo implode(", ", $data[$row]) . "</strong><br /><br />\n";
$Member = BeanFactory::getBean("locte_Members");
$FullName=$Member->full_name_c;
//$myfield_defs = $Member->getFieldDefinitions(); // just to help while developing
//foreach($myfield_defs as $def) echo $def["name"] . "<br />\n";
$Member=$Member->retrieve_by_string_fields(array('full_name_c' => $data[$row]["FULL NAME"]));
if (is_null($Member)) {
$Member = BeanFactory::newBean("locte_Members");
$delta = fillPerson($data[$row], $Member, ""); //->full_name_c, "FULL NAME");
}
if (count($delta)) {
$Member_id = $Member->save();
}
}
// Records have been saved: from this point on, only work on relationships:
$GLOBALS['log']->info('End: Wilderness Import');
myLog('End: Wilderness Import');
time_elapsed();
return true;
}
}
} catch (Exception $e)
{
$GLOBALS['log']->fatal("Wilderness Import: Exception " . $e->getMessage());
myLog("Wilderness Import: Exception " . $e->getMessage());
echo '\n\nCaught exception: ', $e->getMessage(), "\n";
return false;
}
}
It does return info from both the database and the csv file.
Image of error below.
Error - Capture from browser
Help always appreciated :)
This script is throwing error because the parameter $arow given to array_combine is not an array. So a check should be there to check whether $arow is an array or not.
Try code following:
foreach ($data as $i => $arow) {
$GLOBALS['log']->info("Wilderness Import: array_combine " . $i);
if (is_array($arow)) {
$data[$i] = array_combine($fields, $arow);
}
}
Read more about array_combine
Update
Code you are using to read csv need to be changed. Second parameter in fgetcsv must be greater than the longest line (in characters) to be found in the CSV file. So replace code
while (($data[] = fgetcsv($oFile, 0, ', ')) !== FALSE) {
}
with
while (($data[] = fgetcsv($oFile, 10, ', ')) !== FALSE) {
}
Read more about fgetcsv
This block is doing the saving of records using the beanfactory.... I think :|
$Member = BeanFactory::getBean("locte_Members");
$FullName=$Member->full_name_c;
//$myfield_defs = $Member->getFieldDefinitions(); // just to help while developing
//foreach($myfield_defs as $def) echo $def["name"] . "<br />\n";
$Member=$Member->retrieve_by_string_fields(array('full_name_c' => $data[$row]["FULL NAME"]));
if (is_null($Member)) {
$Member = BeanFactory::newBean("locte_Members");
$delta = fillPerson($data[$row], $Member->full_name_c, "FULL NAME");
var_dump($arow);
}
if (count($delta)) {
$Member_id = $Member->save();
}
}
// Records have been saved: from this point on, only work on relationships:
Here's the output of the script in the browser with field definition dump
Wilderness Import Started
Tue, 19 Jun 2018 02:05:56 -0400
Wilderness Import: Scanning XML Data dir custom/wimporter/ToImport...
Wilderness Import: Scanning XML Data dir custom/wimporter/ToImport... [Found 3 files]
Wilderness Import: Processing L1554v4.csv file...
File opened.....
Building CSV File Row Array
Building CSV Header Fields Array as shown below:
LAST NAME, FIRST NAME, FULL NAME
Build Full Array of Roster to be Imported Complete. Entries to be imported are shown below
Filename: L1554v4.csv | Roster Import, Row1:
LAST NAME BUTLER
FIRST NAME BRIANA
FULL NAME BUTLER BRIANA
File Row Data: BUTLER, BRIANA, BUTLER BRIANA
-id
-name
-date_entered
-date_modified
-modified_user_id
-modified_by_name
-created_by
-created_by_name
-description
-deleted
-securitygroup
-securitygroup_display
-created_by_link
-modified_user_link
-assigned_user_id
-assigned_user_name
-assigned_user_link
-additionalusers
-additionalusers_listview
-salutation
-first_name
-last_name
-full_name
-title
-photo
-department
-do_not_call
-phone_home
-email
-phone_mobile
-phone_work
-phone_other
-phone_fax
-email1
-email2
-invalid_email
-email_opt_out
-primary_address_street
-primary_address_street_2
-primary_address_street_3
-primary_address_city
-primary_address_state
-primary_address_postalcode
-primary_address_country
-alt_address_street
-alt_address_street_2
-alt_address_street_3
-alt_address_city
-alt_address_state
-alt_address_postalcode
-alt_address_country
-assistant
-assistant_phone
-email_addresses_primary
-email_addresses
-email_addresses_non_primary
-lcl_birthdate
-lcl_affiliate_number
-member_signature
-ssn
-staff_rep
-mem_join_date
-class_title
-steward
-olo_code
-enterprise_id
-member_card
-address_map
-member_status
-primary_language
-english_speaking
-annual_salary
-currency_id
-state_hire_date
-dues_frequency
-card_sent_date
-gender
-disabilities
-marital_status
-executive_board
-affiliate_type
-middle_name
-name_suffix
-mailableflag
-no_mailflag
-apt_number
-zip4
-infosrc
-lcl_phone_collected
-lcl_hasmobile
-lcl_hasemail
-lcl_member_status
-backofficeassistants
-backoffice_assistant_phonoe
-backoffice_assistant_email
-lcl_employercontact
-lcl_work_dept
-lcl_work_location
-lcl_jobclasstitle
-lcl_employee_id
-lcl_join_date
-lcl_sig_auth
-lcl_dues_status
-lcl_on_probation
-lcl_prob_end_date
-lcl_prob_term
-afs_signed_by
-afs_region_number
-afemp_employers_id_c
-afs_employer
-primary_address_county
-locte_members_adues_dues
-full_name_c
-locte_members_afcbu_cbu
-locte_members_afcbu_cbu_name
-locte_members_afcbu_cbuafcbu_cbu_idb
-ppe_date_c
--- Partial 0.01, Total 0.01 ---
I would like to store dates in a MongoDB collection using PHP et MongoDB Driver.
Here's parts of my scripts :
1st Connexion :
public function process(){
try{
$this->connexion = new \MongoDB\Driver\Manager($this->dsn);
}
catch(\MongoDB\Driver\Exception\InvalidArgumentException $e){
die("Unable to connect to the MongoDB database : " . $e->getMessage());
} catch(\MongoDB\Driver\Exception\RuntimeException $e){
die("General failure : " . $e->getMessage());
}
}
2nd : Document creation
public function process(){
$dbConnector = dbConnector::instance(); // Instance de connexion à la base de données
$query = new \MongoDB\Driver\BulkWrite;
$query->insert($this->queryArray);
$writeConcern = new \MongoDB\Driver\WriteConcern(\MongoDB\Driver\WriteConcern::MAJORITY, 1000);
//$collection = new \MongoCollection($dbConnector->connexion()->db(), $this->store->collectionName());
try{
$this->result = $dbConnector->connexion()->executeBulkWrite($dbConnector->dbName() . "." . $this->store->collectionName(), $query, $writeConcern);
} catch (\MongoDB\Driver\AuthenticationException $e){
echo "Authentication error : " . $e->getMessage() . "<br />\n";
} catch(\MongoDB\Driver\ConnextionException $e){
echo "Connexion error : " . $e->getMessage() . "<br />\n";
}
catch(\MongoDB\Driver\Exception\RuntimeException $e){
echo "Runtime error : " . $e->getMessage() . "<br />\n";
}
}
The $queryArray property contains key/value pairs that i want to create.
Have added a conversion method that can manage dates and converts it into MongoDB ISODate :
use \MongoDB\BSON\UTCDateTime as MongoUTCDate;
...
...
public static function toISODate($date){
if(is_object($date)){
$dateToString = $date->year . "-" . $date->month . "-" . $date->day;
} else {
$dateToString = substr($date,0,10);
}
$initDate = new \DateTime($dateToString);
#begin_debug
#echo "Date from string " . $dateToString . " : " . $initDate->format("d-m-Y") . " (timestamp) " . $initDate->getTimestamp() . "<br />\n";
#end_debug
return new MongoUTCDate($initDate->getTimestamp());
}
My controller works this way :
$stats->_id = $this->requestData()->_id;
$stats->purchases = [array(
"date" => \wp\Database\MongoDB\Utilities\MongoDate::toIsoDate($this->requestData()->date),
"coords" => array("lat" => $this->requestData()->coords->lat, "lon" => $this->requestData()->coords->lon),
"metar" => null,
"quantity" => $this->requestData()->quantity,
"price" => (float) $this->requestData()->price,
"peremption" => \wp\Database\MongoDB\Utilities\MongoDate::toIsoDate($this->requestData()->peremption)
)];
$stats->insert();
When called, document is correctly created but dates are wrong :
{
"_id" : "3256222010007",
"purchases" : [
{
"date" : ISODate("1970-01-18T07:43:01.706Z"),
"coords" : {
"lat" : 43.7294742,
"lon" : 1.416332
},
"metar" : null,
"quantity" : 1,
"price" : 2.87,
"peremption" : ISODate("1970-01-18T22:20:34.800Z")
}
]
}
In the previous example, dates would be i.e. the date of the day...
When i log datas, i saw that dates are correctly formed in PHP :
Date from string 2017-06-04 : 04-06-2017 (timestamp) 1496527200<br />
If convert back timestamp, got the correct date... so, don't understand why Mongo dates are incorrect.
For those experiments the same issue, just multiply by 1000 the timestamp given by PHP :
public static function toISODate($date){
if(is_object($date)){
$dateToString = $date->year . "-" . $date->month . "-" . $date->day;
} else {
$dateToString = substr($date,0,10);
}
$initDate = new \DateTime($dateToString);
#begin_debug
#echo "Date récupérée à partir de " . $dateToString . " : " . $initDate->format("d-m-Y") . " (timestamp) " . $initDate->getTimestamp() . "<br />\n";
#end_debug
$stampedDate = $initDate->getTimestamp() * 1000;
$mongoUTCDate = new MongoUTCDate($stampedDate);
return $mongoUTCDate;
}
The correct date is stored...
The LogMeIn API's "getSession" call is driving me a bit crazy. According to their documentation, you should be able to input an iNodeID either from the getHierarchy call or just the tech's ID# from the LogMeIn admin page and it will report their open session information, but no matter what I use, I get an error "stdClass Object ( [getSessionResult] => getSession_InvalaidParam_NodeID )" Has anyone ever seen this?
Here is my code:
<?php
require("/usr/local/lib/php/nusoap/nusoap.php");
$loginParams = array(
'sEmail' => *hidden*,
'sPassword' => *hidden*
);
$soapclient = new soapclient("https://secure.logmeinrescue.com/API/API.asmx?WSDL");
$loginResult = $soapclient->login($loginParams);
$hierparams = array(""=>"");
$hierarchyResult = $soapclient->getHierarchy($hierparams);
$hierarchy = $hierarchyResult->aHierarchy;
$nodes = $hierarchy->HIERARCHY;
$numberofnodes = count($nodes);
echo "<table border =\"0\" cellspacing = \"5\">";
for ($iNodes = 0; $iNodes < $numberofnodes; $iNodes += 1)
{
if($nodes[$iNodes]->eStatus == "Online" && $nodes[$iNodes]->eType == "Technician"){
print_r("<tr>");
print_r("<td>Name: " . $nodes[$iNodes]->sName . "<br /></td>");
####This works
print_r("<td>ID: " . $nodes[$iNodes]->iNodeID . "<br /></td>");.
###############
print_r("<td>Email: " . $nodes[$iNodes]->sEmail . "<br /></td>");
####This doesn't.
$sessioninfo = $soapclient->getSession($nodes[$iNodes]->iNodeID);
################
print_r("<td>Session Dump: ". print_r($sessioninfo) . "</td>");
print_r("</td>");
}
}
print_r("</table>");
$soapclient->logout();
?>
Turns out there was a parameter that I overlooked, eNodeRef, which has a default parameter of "NODE".
$iNodeID = $nodes[$iNodes]->iNodeID;
$eNodeRef = "NODE";
$sessionparams = array(
'iNodeID' => $iNodeID,
'eNodeRef' => $eNodeRef
);
$sessionresult = $soapclient->getSession($sessionparams);