PHP SoapClient not getting substructures - php

I'm trying to get the response of A SOAP Service, but I can't get the subcollections data.
When I call the ws method using a soap client software I get the next response:
<WSGLMSuit.METHODNAME xmlns="http://tempuri.org/">
<Sdtpolizadetalle>
<Empresa>1</Empresa>
<DscEmpresa>TEST</DscEmpresa>
<Rama>22</Rama>
<DscRama>COMBINADO FAMILIAR</DscRama>
<Poliza>000000</Poliza>
<DscRiesgo/>
<InicioVigencia>2019-03-18</InicioVigencia>
<FinVigencia>2019-09-18</FinVigencia>
<Productor>3311</Productor>
<NombreProductor>TEST</NombreProductor>
<Tomador>
<CodTomador>336028</CodTomador>
<NombreTomador>TEST</NombreTomador>
<Domicilio>SAAVEDRA 1174 Dpto. 0</Domicilio>
<Localidad>TRES ARROYOS</Localidad>
<CodigoPostal>7500</CodigoPostal>
</Tomador>
<DscMoneda>PESOS</DscMoneda>
<CantidadCuotas>3</CantidadCuotas>
<Suplementos>
<Suplemento>
<Suplemento>0</Suplemento>
<TipoOperacion>02</TipoOperacion>
<SubTipoOperacion>000</SubTipoOperacion>
<DscOperacion>GENERAL</DscOperacion>
<InicioVigencia>2019-03-18</InicioVigencia>
<FinVigencia>2019-09-18</FinVigencia>
<Prima>2515.95</Prima>
<Premio>3104.68</Premio>
<Cuotas>
<Cuota>
<NroCuota>1</NroCuota>
<Vencimiento>2019-03-18</Vencimiento>
<Estado>Pagada</Estado>
<Importe>519.68</Importe>
<NroCupon>1</NroCupon>
</Cuota>
<Cuota>
<NroCuota>2</NroCuota>
<Vencimiento>2019-04-18</Vencimiento>
<Estado>Vencida</Estado>
<Importe>517.00</Importe>
<NroCupon>2</NroCupon>
</Cuota>
<Cuota>
<NroCuota>3</NroCuota>
<Vencimiento>2019-05-18</Vencimiento>
<Estado>Impaga</Estado>
<Importe>517.00</Importe>
<NroCupon>3</NroCupon>
</Cuota>
</Cuotas>
</Suplemento>
</Suplementos>
</Sdtpolizadetalle>
<Sesionexpirada>false</Sesionexpirada>
</WSGLMSuit.METHODNAMEResponse>
So, I made a function in PHP with SoapClient class to make same request and get the result parsed as JSON but it doesn't giving me the "Suplementos" collection and its data.
{
"Sdtpolizadetalle": {
"Empresa": 1,
"DscEmpresa": "TEST",
"Rama": 22,
"DscRama": "COMBINADO FAMILIAR",
"Poliza": 129031,
"DscRiesgo": "",
"InicioVigencia": "2019-03-18",
"FinVigencia": "2019-09-18",
"Productor": 3311,
"NombreProductor": "TEST",
"Tomador": {
"CodTomador": 336028,
"NombreTomador": "TEST",
"Domicilio": "SAAVEDRA 1174 Dpto. 0",
"Localidad": "TRES ARROYOS",
"CodigoPostal": "7500"
},
"DscMoneda": "PESOS",
"CantidadCuotas": 3,
"Suplementos": {} // <--- HERE IS THE ISSUE
},
"Sesionexpirada": false
}
The PHP function is:
$wsdl = "http://wsdlservice.org?wsdl";
$params = $request->getParsedBody();
$options = array(
'soap_version' => SOAP_1_2,
'style' => SOAP_DOCUMENT,
'use' => SOAP_LITERAL,
'exceptions' => true,
'trace' => 1,
'cache_wsdl' => WSDL_CACHE_NONE,
'encoding' => 'UTF-8'
);
$soap = new SoapClient($wsdl, $options);
$clientRes = $soap->METHODNAME($params);
return json_encode($clientRes, JSON_PRETTY_PRINT);

Finally I got a solution. I found a function for parsing XML string to Array. So what I do is get the response as XML, save it into a file and parse it with that function. Code better than words:
function xmlToArray($xml, $options = array())
{
$defaults = array(
'namespaceSeparator' => ':',
'attributePrefix' => '#',
'alwaysArray' => array(),
'autoArray' => true,
'textContent' => '$',
'autoText' => true,
'keySearch' => false,
'keyReplace' => false
);
$options = array_merge($defaults, $options);
$namespaces = $xml->getDocNamespaces();
$namespaces[''] = null;
$attributesArray = array();
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
if ($options['keySearch']) $attributeName =
str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
$attributeKey = $options['attributePrefix']
. ($prefix ? $prefix . $options['namespaceSeparator'] : '')
. $attributeName;
$attributesArray[$attributeKey] = (string)$attribute;
}
}
$tagsArray = array();
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->children($namespace) as $childXml) {
$childArray = xmlToArray($childXml, $options);
list($childTagName, $childProperties) = each($childArray);
if ($options['keySearch'])
$childTagName = str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
if ($prefix)
$childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
if (!isset($tagsArray[$childTagName])) {
$tagsArray[$childTagName] =
in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
? array($childProperties)
: $childProperties;
} elseif (
is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
=== range(0, count($tagsArray[$childTagName]) - 1)
) {
$tagsArray[$childTagName][] = $childProperties;
} else {
$tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
}
}
}
$textContentArray = array();
$plainText = trim((string)$xml);
if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;
$propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;
return array(
$xml->getName() => $propertiesArray
);
}
$params = array('key' => 'value') // params needed to make the request
$options = array(
'trace' => 1,
'exceptions' => true
);
try {
$soap = new SoapClient($url, $options);
$soap->method($params); // replace method name
$xmlResponse = $soap->__getLastResponse();
} catch (Exception $e) {
die(
json_encode(
[
'error' => 'Cannot request to WS. ' . $e->getMessage()
]
)
);
// save the response into an xml file for parse
// it and return its content as json
if (file_put_contents('response.xml', $xmlResponse)) {
$xmlNode = simplexml_load_file($this->tempPath);
$arrayData = xmlToArray($xmlNode);
unlink('response.xml');
return json_encode($arrayData, JSON_PRETTY_PRINT);
} else {
return json_encode(['error' => 'Error saving the response into file.']);
}

Related

How to read 2 dimensional array data using Google Sheets API?

i'm new to Google Sheets API,
currently i am develop a system to send data to google sheets.
And while im trying to send the data, it shows error like: Invalid values [0][0]
Below is my code line.
`
$client = getClientAuth();
$spreadsheet_ID = $this->spreadsheet->spreadsheetId;
$range = "Sheet1";
$values = $this->sheetData;
$this->service = new Sheets($client);
$body = new ValueRange([
'majorDimension' => 'ROWS',
'values' => [array_map(function($nv) {
return (is_null($nv)) ? "" : $nv;
},$values)]
]);
$params = ['valueInputOption' => 'RAW'];
$insert = ['insertDataOption' => 'INSERT_ROWS'];
//executing the request
$data = $this->service->spreadsheets_values->append($spreadsheet_ID, $range,
$body, $params, $insert);
return $data;
`
From your error message and your showing script, I thought that in your situation, $values might be a 2-dimensional array. I think that if $values is a 1-dimensional array, your script works. And also, please include 'insertDataOption' => 'INSERT_ROWS' in $params. So, in this case, how about the following modification?
From:
$body = new ValueRange([
'majorDimension' => 'ROWS',
'values' => [array_map(function($nv) {
return (is_null($nv)) ? "" : $nv;
},$values)]
]);
$params = ['valueInputOption' => 'RAW'];
$insert = ['insertDataOption' => 'INSERT_ROWS'];
//executing the request
$data = $this->service->spreadsheets_values->append($spreadsheet_ID, $range,
$body, $params, $insert);
To:
$body = new ValueRange([
'majorDimension' => 'ROWS',
'values' => array_map(function($row) {
return array_map(function($col) {
return (is_null($col)) ? "" : $col;
}, $row);
}, $values)
]);
$params = ['valueInputOption' => 'RAW', 'insertDataOption' => 'INSERT_ROWS'];
$data = $service->spreadsheets_values->append($spreadsheet_ID, $range, $body, $params);
or
$body = new Google_Service_Sheets_ValueRange([
'majorDimension' => 'ROWS',
'values' => array_map(function($row) {
return array_map(function($col) {
return (is_null($col)) ? "" : $col;
}, $row);
}, $values)
]);
$params = ['valueInputOption' => 'RAW', 'insertDataOption' => 'INSERT_ROWS'];
$data = $service->spreadsheets_values->append($spreadsheet_ID, $range, $body, $params);
Note:
When the arrow function is used, I think that the following modification can be used.
From
'values' => array_map(function($row) {
return array_map(function($col) {
return (is_null($col)) ? "" : $col;
}, $row);
}, $values)
To
'values' => array_map(fn($row) => array_map(fn($col) => (is_null($col)) ? "" : $col, $row), $values)

Cannot solve Requests_Exception_Transport_cURL [ PHP & Wordpress Error]

I'm getting "Undefined property: Requests_Exception_Transport_cURL::$status_code" error and failed to solve it.
private function do_bulk_api_call( $endpoint, $data=array(), $version=0 ) {
if( !$this->cmcapi['status'] )
return false;
$final_api_data = $bulk_requests = array();
$options = get_option( 'cmcapi' );
$version = $version ? $version : $this->cmcapi['version'];
$bulk_url = $this->cmcapi['url'] . $version . $endpoint;
if( $data && is_array($data) ):
foreach ($data as $k => $chunk) {
// TEMP condition
// if( $k > 0 )
// continue;
$bulk_requests[] = array(
'type' => 'GET',
'timeout' => 90,
'url' => $bulk_url,
'headers' => array(
'X-CMC_PRO_API_KEY' => $this->cmcapi['key'],
),
'data' => array( 'id' => implode(',',$chunk) )
);
}
endif;
$requests = Requests::request_multiple( $bulk_requests );
foreach ($requests as $key => $response) {
if($response->status_code !== 200) {
continue;
}
$res_decoded = json_decode($response->body);
$this->kte_shipment_api_results[$key] = array();
$final_api_data = array_merge( (array) $final_api_data, (array) $response->data );
if( !$res_decoded->status->error_code && is_object($res_decoded->data) ){
$final_api_data = array_merge( (array) $final_api_data, (array) $res_decoded->data );
}
}
return $final_api_data;
}
By the way, this code is from other teammate and he is gone now so I cannot ask to him.

Hello how do I insert API response into my MySQL database

Hi I'm trying to insert API response into my MySQL database. i have converted the data into json format and I'm passing the data to mysql db using the code below each time I try to run the code 0 are inserted to mydb instead of real values
<?php
class MagnusBilling
{
protected $api_key;
protected $api_secret;
public $public_url;
public $filter = [];
public $result = [];
public function __construct($api_key, $api_secret)
{
$this->api_key = $api_key;
$this->api_secret = $api_secret;
}
public function query(array $req = array())
{
// API settings
$key = $this->api_key;
$secret = $this->api_secret;
$trading_url = $this->public_url;
$module = $req['module'];
$action = $req['action'];
// generate a nonce to avoid problems with 32bit systems
$mt = explode(' ', microtime());
$req['nonce'] = $mt[1] . substr($mt[0], 2, 6);
// generate the POST data string
$post_data = http_build_query($req, '', '&');
$sign = hash_hmac('sha512', $post_data, $secret);
// generate the extra headers
$headers = array(
'Key: ' . $key,
'Sign: ' . $sign,
);
static $ch = null;
if (is_null($ch)) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$ch,
CURLOPT_USERAGENT,
'Mozilla/4.0 (compatible; MagnusBilling PHP bot; ' . php_uname('a') . '; PHP/' . phpversion() . ')'
);
}
curl_setopt($ch, CURLOPT_URL, $trading_url . '/index.php/' . $module . '/' . $action);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// run the query
$res = curl_exec($ch);
if ($res === false) {
throw new Exception('Curl error: ' . curl_error($ch));
}
$dec = json_decode($res, true);
if (!$dec) {
print_r($res);
exit;
} else {
return $dec;
}
}
public function create($module, $data = [])
{
$data['module'] = $module;
$data['action'] = 'save';
$data['id'] = 0;
return $this->query($data);
}
public function update($module, $id, $data)
{
$data['module'] = $module;
$data['action'] = 'save';
$data['id'] = $id;
return $this->query($data);
}
public function destroy($module, $id)
{
return $this->query(
array(
'module' => $module,
'action' => 'destroy',
'id' => $id,
)
);
}
public function read($module, $page = 1, $action = 'read')
{
return $this->query(
array(
'module' => $module,
'action' => $action,
'page' => $page,
'start' => $page == 1 ? 0 : ($page - 1) * 25,
'limit' => 25,
'filter' => json_encode($this->filter),
'filter' => json_encode($this->result),
)
);
}
public function buyDID($id_did, $id_user)
{
return $this->query(
array(
'module' => 'did',
'action' => 'buy',
'id' => $id_did,
'id_user' => $id_user,
)
);
}
public function getFields($module)
{
return $this->query(
array(
'module' => $module,
'getFields' => 1,
)
);
}
public function createUser($data)
{
$data['createUser'] = 1;
$data['id'] = 0;
return $this->query($data);
}
public function getModules()
{
return $this->query(
array(
'getModules' => 1,
)
);
}
public function getMenu($username)
{
return $this->query(
array(
'username' => $username,
'getMenu' => 1,
)
);
}
public function getId($module, $filed, $value)
{
$this->setFilter($filed, $value, 'eq');
$query = $this->query([
'module' => $module,
'action' => 'read',
'page' => 1,
'start' => 0,
'limit' => 1,
'filter' => json_encode($this->filter),
]);
$this->filter = [];
if (isset($query['rows'][0])) {
return $query['rows'][0]['id'];
}
}
public function clearFilter()
{
$this->filter = [];
}
public function setFilter($field, $value, $comparison = 'st', $type = 'string')
{
$this->filter[] = (object) [
'type' => $type,
'field' => $field,
'value' => $value,
'comparison' => $comparison,
];
}
}
$connect = mysqli_connect("localhost", "root", "", "api");
$magnusBilling = new MagnusBilling('92b1c021402efd293fd4b3fd0', ' 1178f001b001e29c9b7a15a1f');
$magnusBilling->public_url = "http://voip/mbilling"; // Your MagnusBilling URL
$result = $magnusBilling->read('callerid');
// Convert the JSON String into PHP Array
$array = json_decode($result, true);
// Extracting row by row
foreach($array as $row) {
// Database query to insert data
// into database Make Multiple
// Insert Query
$query .=
"INSERT INTO account VALUES
('".$row["id"]."', '".$row["cid"]."',
'".$row["name"]."'); ";
$table_data .= '
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["cid"].'</td>
<td>'.$row["name"].'</td>
</tr>
'; // Data for display on Web page
}
if(mysqli_multi_query($connect, $query)) {
echo '<h3>Inserted JSON Data</h3><br />';
echo '
<table class="table table-bordered">
<tr>
<th width="45%">id</th>
<th width="10%">cid</th>
<th width="45%">name</th>
</tr>
';
echo $table_data;
echo '</table>';
}
?>
this is the response am trying to insert into mysql db
{ "rows": [ { "id": "1", "cid": "25411188205", "name": "Nairobi
Muslim Academy", "description": "", "id_user": "3", "activated": "1",
"idUserusername": "67800" } ], "count": "1", "sum": false }
In your case your $result is {"rows":....}, so you should not use foreach($array ...), you should use foreach($array['rows'] as $row) instead.

Zabbix Reading the Api

I'm getting Informations from the Zabbix Api with a PHP library. At the moment I get the "lastvalue" from the json Array:
try {
// connect to Zabbix-API
$api = new ZabbixApi($api_url, $username, $password);
$params = array(
'groupids' => '2',
'real_items' =>TRUE,
'monitored_items' =>TRUE,
'search' => array('name' => 'Disk root used p'),
'selectFunctions' => 'extend',
'output' => 'extend',
'sortfield' => 'name',
'limit' => '1'
);
$trends = $api->itemGet($params); // get data from api
$names = array();
foreach($trends as $trend) { // loop through the returned data
$names[] = $trend->lastvalue;
}
//print_r($names);
} catch(Exception $e) {
// Exception in ZabbixApi catched
echo $e->getMessage();
}
But now I want to get the "lastvalue" plus the "name" of the Item in this Array for example like that: "name"+"lastvalue". How can I get both of them into my array $names[]?
Here is my answer from my comments, hope its what you are looking for!
$trends = $api->itemGet($params);
$names = array();
foreach($trends as $trendKey => $trendValue)
{
$names[$trendKey] = $trendValue;
}
#Test the names array
foreach ($names as $nameKey => $nameValue)
{
print("{$nameKey} = {$nameValue}<br />");
}
Return value:
groupids = 2
real_items = TRUE
...
sortfield = name
limit = 1

How to get vSphere host name rather than host id?

I have a script (below) which connects to a vCenter and pulls off all of the VMs and what host they are currently on. The only thing is it only gives me the host ID not the name. Is there any way to get the name as well or lookup the name after it has got the id?
<?php
class soapclientd extends soapclient
{
public $action = false;
public function __construct($wsdl, $options = array())
{
parent::__construct($wsdl, $options);
}
public function __doRequest($request, $location, $action, $version, $one_way = 0)
{
$resp = parent::__doRequest($request, $location, $action, $version, $one_way);
return $resp;
}
}
$client = new SoapClient("https://192.168.1.103/sdk/vimService.wsdl", array("trace" => 1, "location"=>"https://192.168.1.103/sdk"));
try
{
$request = new stdClass();
$request->_this = array ('_' => 'ServiceInstance', 'type' => 'ServiceInstance');
$response = $client->__soapCall('RetrieveServiceContent', array((array)$request));
}
catch (Exception $e)
{
echo $e->getMessage();
exit;
}
$ret = $response->returnval;
try
{
$request = new stdClass();
$request->_this = $ret->sessionManager;
$request->userName = 'root';
$request->password = 'vmware';
$response = $client->__soapCall('Login', array((array)$request));
}
catch (Exception $e)
{
echo $e->getMessage();
exit;
}
$ss1 = new soapvar(array ('name' => 'FolderTraversalSpec'), SOAP_ENC_OBJECT, null, null, 'selectSet', null);
$ss2 = new soapvar(array ('name' => 'DataCenterVMTraversalSpec'), SOAP_ENC_OBJECT, null, null, 'selectSet', null);
$a = array ('name' => 'FolderTraversalSpec', 'type' => 'Folder', 'path' => 'childEntity', 'skip' => false, $ss1, $ss2);
$ss = new soapvar(array ('name' => 'FolderTraversalSpec'), SOAP_ENC_OBJECT, null, null, 'selectSet', null);
$b = array ('name' => 'DataCenterVMTraversalSpec', 'type' => 'Datacenter', 'path' => 'vmFolder', 'skip' => false, $ss);
$res = null;
try
{
$request = new stdClass();
$request->_this = $ret->propertyCollector;
$request->specSet = array (
'propSet' => array (
array ('type' => 'VirtualMachine', 'all' => 0, 'pathSet' => array ('name','runtime.powerState', 'config.hardware.numCPU', 'config.hardware.memoryMB', 'runtime.host')),
),
'objectSet' => array (
'obj' => $ret->rootFolder,
'skip' => false,
'selectSet' => array (
new soapvar($a, SOAP_ENC_OBJECT, 'TraversalSpec'),
new soapvar($b, SOAP_ENC_OBJECT, 'TraversalSpec'),
),
)
);
$res = $client->__soapCall('RetrieveProperties', array((array)$request));
}
catch (Exception $e)
{
echo $e->getMessage();
}
$tvCPU = 0;
$tvRAM = 0;
echo "<table><tr><td width='450px'>Name</td> <td width='100px'>vRAM (MB)</td><td width='100px'>vCPU</td><td width='100px'>Power State</td><td width='100px'>Host</td> </tr>";
$arrlength=count($res ->returnval);
for($x=0;$x<$arrlength;$x++)
{
$name = $res -> returnval[$x] -> propSet[2]->val;
$vRam = $res -> returnval[$x] -> propSet[0]->val;
$vCPU = $res -> returnval[$x] -> propSet[1]->val;
$pState = $res -> returnval[$x] -> propSet[4]->val;
$host = $res -> returnval[$x] -> propSet[3]->val->_;
echo "<tr><td width='450px'>".$name.
"</td><td>".$vRam.
"</td><td>".$vCPU.
"</td> <td>".$pState.
"</td> <td>".$host.
"</td></tr>";
$tvCPU = $tvCPU + $vCPU;
$tvRAM = $tvRAM + $vRam;
}
echo "<tr><td width='450px'>Total VMs - ".$x."</td><td>". $tvRAM."</td><td>". $tvCPU."</td></tr>";
?>

Categories