Fatal error: cannot use stdClass as array - php

I've inherited some code from an ex-colleague and as it has recently been put into production it is causing us some issues. I'm not a php developer so apologies if this appears vague but it has fallen to me (don't ask!).
We are calling a function getLoan() to pre-populate an application form from an existing application. This should return an array, but I am receiving the stdClass error.
$result = getLoan(); //this is the line that is erroring
if (isset($result->GetResult->Debtor->Addresses->Address[0])) $current_address = clone $result->GetResult->Debtor->Addresses->Address[0];
else $current_address = clone $result->GetResult->Debtor->Addresses->Address;
if ($result === false)
{
echo("No LID given");
die;
}
$attr = 'selected';
and the function:
function getLoan() {
//globals
/*
global $client;
global $test;
global $result;
*/
global $thisurl;
if (isset($_GET['LID']))
$pLoanID = $_GET['LID'];
else
return false;
$test = array(
"pLoanID" => $pLoanID,
);
//print_r($Address); //print address object as a test
//send to gateway starts**********
$url = "https://www.blahblah.asmx?WSDL";
$client = new SoapClient($url, array("trace" => 1, "exception" => 0));
try {
$result = $client->Get($test);
}
catch(Exception $e) {
//header("Location: http://" . $_SERVER['REMOTE_ADDR'] . "/application-form-new");
print_r($e);
exit;
}
$thisurl = "continue-app?LID=" . $pLoanID;
if (isset($result)) return $result;
else return false;
}
How can I assign the returned value from the function to $result as an array?
Many thanks

array = json_decode(json_encode(object),true);

Related

How can i modify my array code to complete even if a value does not exist in the array?

I am modifying some code i had written for my by a developer who is no longer working with us, essentially the code pulls data from a web service and parses to an array, it then looks for keys within the array and publishes associated values to an HTML table, it all works fine when each of the entries exists in the data however the point of modifying the code if to return a generic value ("not submitted") if the value is not found in the array.
background info is helpful so the use case is:
Array is made up of the sales team, they each login to a website and submit their sales totals for the day, we interrogate the web service to return the data via a SOAP call which pulls the data into the code. The data is parsed and the values are represented in a table on a web page.
If a single sales team member does not submit data then the code fails to return any data.
I've been googling and hitting my pluralsight account to learn as much as i can about how this is done but i'm falling short.
class SalesResponseFactory
{
private $date;
//private $keyArray = ['KE', 'JY', 'OR', 'KR', 'SY', 'DB'];
public $responseData = [];
function __construct($date)
{
libxml_use_internal_errors(true);
$this->date = $date;
}
private function getResponseData($date)
{
....
}
private function parserToArray($data)
{
$data = substr($data, strpos($data, "<DataResult>"));
$data = substr($data, 0, strpos($data, "</DataResult>") + strlen("</DataResult>"));
$xml = simplexml_load_string($data);
if ($xml === false) {
throw new Exception("Invalid user credentials.");
}
$json = json_encode($xml);
$array = json_decode($json,TRUE);
if (empty($array['Results'])) {
throw new Exception("Holiday - No Sales Data Recorded");
}
return $array['Results']['Data'];
}
private function alignmentArray($sales)
{
if ($sales['Name'] == 'Market Code' || $sales['Name'] == 'Sales Volume' || $sales['Name'] == 'Turnover Volume' || $sales['Name'] == 'Date') {
if($sales['Name'] == 'Market Code') {
$this->responseData[$sales['Instrument']]['Market Code'] = $sales['Value'];
}
if($sales['Name'] == 'Sales Volume') {
$this->responseData[$sales['Instrument']]['Sales Volume'] = $sales['Value'];
}
if($sales['Name'] == 'Turnover Volume') {
$this->responseData[$sales['Instrument']]['Turnover Volume'] = $sales['Value'];
}
else {
$this->responseData[$sales['Instrument']]['Date'] = $sales['Value'];
}
}
}
public function parser()
{
try {
$salesArray = $this->getResponseData($this->date);
} catch (Exception $e) {
$response['status'] = 'error';
$response['message'] = $e->getMessage();
$response['results'] = '';
return json_encode($response);
}
foreach ($salesArray as $sales) {
$this->alignmentArray($sales);
}
$response['status'] = 'ok';
$response['message'] = 'success';
$response['results'] = [];
foreach ($this->responseData as $row) {
array_push($response['results'], $row);
}
return json_encode($response);
}
}
?>
i'd expect that null values should still be output but whats actually happening is that no data is being returned to the HTML table.

JSON decode not decoding correctly php

I have a PHP function that talks to another API for real-time train information to get data from it. It makes the call and parses the XML data to JSON but when there is only one train in the station it will come out as an object and not an array. How can I make it convert everything to an array even if there is only one train coming.
public function getStationsByName(Request $request)
{
try {
$stationName = $request->input('id');
$url = "http://api.irishrail.ie//realtime/realtime.asmx/getStationDataByNameXML?StationDesc=";
$url .= $stationName;
$res['status'] = true;
$res['message'] = 'Success';
$ir = xmlparser::Parse($url);
$res ['results'] = json_decode($ir, TRUE);
$res['num_rows'] = count($res['results']);
return response($res, 200);
} catch (\Illuminate\Database\QueryException $ex) {
$res['status'] = false;
$res['message'] = $ex->getMessage();
return response($res, 500);
}
}
This is what the data looks like with more than one train arriving at the station
And this is where there is only one arriving
You can check it by your self,
if(false !== ($result = json_decode($ir, TRUE))){
if(isset($result["objStationData"]["Servertime"])){
$objStationDatas = [$result["objStationData"]];
}else{
$objStationDatas = $result["objStationData"];
}
}
before convert JSON into array you can check if the parsed XML is an array or an object. You have to do that on your objStationData the code below is just an example
if(!is_array($ir){
$res ['results'] = json_decode($ir, TRUE);
}else{
$res ['results'] = $ir;
}
or
if(is_object($ir){
$res ['results'] = json_decode($ir, TRUE);
}else{
$res ['results'] = $ir;
}

PHP get link from txtfile, unset this link inside the array and get random array value

I'm trying to load a website url from a textfile, then unset this string from an array and pick a random website from the array.
But once I try to access the array from my function the array would return NULL, does someone know where my mistake is located at?
My current code looks like the following:
<?php
$activeFile = 'activeSite.txt';
$sites = array(
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
);
function getActiveSite($file)
{
$activeSite = file_get_contents($file, true);
return $activeSite;
}
function unsetActiveSite($activeSite)
{
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}
function updateActiveSite($activeFile)
{
$activeWebsite = getActiveSite($activeFile);
if(!empty($activeWebsite))
{
$unsetActive = unsetActiveSite($activeWebsite);
if($unsetActive == true)
{
$randomSite = $sites[array_rand($sites)];
return $randomSite;
}
else
{
echo 'Could not unset the active website.';
}
}
else
{
echo $activeWebsite . ' did not contain any active website.';
}
}
$result = updateActiveSite($activeFile);
echo $result;
?>
$sites is not avaliable in unsetActiveSite function you need to create a function called "getSites" which return the $sites array and use it in unsetActiveSite
function getSites(){
$sites = [
'http://wwww.google.com',
'http://www.ebay.com',
'http://www.icloud.com',
'http://www.hackforums.net',
'http://www.randomsite.com'
];
return $sites;
}
function unsetActiveSite($activeSite)
{
$sites = getSites();
if(($key = array_search($activeSite, $sites)) !== false)
{
unset($sites[$key]);
return true;
}
else
{
return false;
}
}

bluedart api pincode search not working in php for api integration

Any one please to help me i have one problem in blue dart api error. NO Error is came. how to solve this problem.
require_once('lib/nusoap.php');
function soaprequest($api_url, $api_username, $api_password, $service, $params)
{
if ($api_url != '' && $service != '' && count($params) > 0)
{
$wsdl = $api_url."?wsdl";
$client = new nusoap_client($wsdl, 'wsdl');
$client->setCredentials($api_username,$api_password);
$error = $client->getError();
if ($error)
{
echo "\nSOAP Error\n".$error."\n";
return false;
}
else
{
$result = $client->call($service, $params);
if ($client->fault)
{
print_r($result);
return false;
}
else
{
$result_arr = json_decode($result, true);
$return_array = $result_arr['result'];
return $return_array;
}
}
}
}
$api_url = "http://netconnect.bluedart.com/ver1.7/Demo/ShippingAPI/Finder/ServiceFinderQuery.svc?wsdl";
//$api_url = "http://netconnect.bluedart.com/ Demo/ShippingAPI/Finder/ServiceFinderQuery.svc?wsdl";
$api_username='XXXXXXXXXX';
$api_password = 'AAAAAAAAAAAAAAAAAAAAAAA';
$service ='GetServicesforPincode';
$params = array('pinCode'=>'620102');
soaprequest($api_url, $api_username, $api_password, $service, $params);
above code is download from codeigniter library and it have also not working
the url you are supplying terminates with ?wsdl but inside the soaprequest function ?wsdl gets appended to the url so I guess your url would look like
http://netconnect.bluedart.com/ver1.7/Demo/ShippingAPI/Finder/ServiceFinderQuery.svc?wsdl?wsdl
which doesn't seem right so try without the ?wsdl at the end of the url?

Session data changed in php

This is my code
class WcfClient {
public $wcfClient = null;
public $user = null;
public function __construct(){
if(isset($_SESSION['APIClient']) && $_SESSION['APIClient'] != null){
$this->wcfClient = $_SESSION['APIClient'];
}
}
public function __destruct(){
}
// Authanticate
private function Authenticate(){
global $_sogh_soapUrl, $_isDebug, $_sogh_header;
$wcargs = array();
$consumerAuthTicket = null;
if($this->wcfClient == null){
$args = array(
'clubname'=>'Wellness Institute at Seven Oaks',
'consumerName'=>'api',
'consumerPassword'=>'api'
);
try{
$wcargs = array(
'soap_version'=>SOAP_1_2
);
if($_isDebug){
$wcargs = array(
'soap_version'=>SOAP_1_2,
'proxy_host'=>"192.168.0.1",
'proxy_port'=>8080
);
}
// Connect to the API with soapclient
$soapAPIClient = new SoapClient($_sogh_soapUrl, $wcargs);
$response = $soapAPIClient->AuthenticateClubConsumer($args);
if(isset($response->AuthenticateClubConsumerResult)){
if(isset($response->AuthenticateClubConsumerResult->IsException) && $response->AuthenticateClubConsumerResult->IsException == true){
// some error occur
$this->wcfClient = null;
$_SESSION['APIClient'] = $this->wcfClient;
} else{
// set consumer ticket
$consumerAuthTicket = $response->AuthenticateClubConsumerResult->Value->AuthTicket;
// $loginData = $responseCode->ReturnValueOfConsumerLoginData;
$headers = array();
$headers[] = new SoapHeader($_sogh_header, "ConsumerAuthTicket", $consumerAuthTicket);
$soapAPIClient->__setSoapHeaders($headers);
// add to session
$this->wcfClient = $soapAPIClient;
$_SESSION['APIClient'] = $this->wcfClient;
}
}
} catch(SoapFault $fault){
$this->error('Fault: ' . $fault->faultcode . ' - ' . $fault->faultstring);
} catch(Exception $e){
$this->error('Error: ' . $e->getMessage());
}
}
return $this->wcfClient;
}
I store the soap client object in $_SESSION['APIClient'], but second times when run some data has been changed in session, I am use this class in drupal 7, I want to save the time using session, because authenticating takes long time.
Please help
Thank in advance

Categories