Zoho CRM API simpleXMLelement get multiple product IDs - php

I am working with the Zoho CRM api and I was able to extract the product ID when only inserting one product, but can't figure out how to do it with multiple products. https://www.zoho.com/crm/help/api/insertrecords.html#Insert_Multiple_records
I convert the response to simpleXMLElement and I can get the first product ID easily with:
...curl stuff
$data = curl_exec($ch);
$xml = new SimpleXMLElement($data);
$product_id = $xml->result->recorddetail->FL[0];
The question is if I have multiple product ID's sent back how would I get each one in a loop as my code will only return the first product ID successfully. This is an example of the response from 2 products inserted in the api and the returned response:
SimpleXMLElement Object ( [#attributes] => Array ( [uri] =>
/crm/private/xml/Products/insertRecords ) [result] => SimpleXMLElement
Object ( [message] => Record(s) added successfully [recorddetail] => Array (
[0] => SimpleXMLElement Object ( [FL] => Array ( [0] => **2389399000000122065**
[1] => 2017-03-12 21:33:50 [2] => 2017-03-12 21:33:50 [3] =>
SimpleXMLElement Object ( [#attributes] => Array ( [val] => Created By ) )
[4] => SimpleXMLElement Object ( [#attributes] => Array ( [val] => Modified
By ) ) ) ) [1] => SimpleXMLElement Object ( [FL] => Array ( [0] =>
**2389399000000122066** [1] => 2017-03-12 21:33:50 [2] => 2017-03-12 21:33:50
[3] => SimpleXMLElement Object ( [#attributes] => Array ( [val] => Created
By ) ) [4] => SimpleXMLElement Object ( [#attributes] => Array ( [val] =>
Modified By ) ) ) ) ) ) )
Not sure if it shows up in bold but the two values enclosed in ** ** is what I am looking to extract.

The key to this is to understand that this:
$xml->result->recorddetail->FL[0];
Is just shorthand for this:
$xml->result[0]->recorddetail[0]->FL[0];
That should make it obvious that to access the 2nd recorddetail (with index 1), you could write this:
$xml->result->recorddetail[1]->FL[0];
Because of the magic SimpleXML provides you can also find out how many there are:
count($xml->result->recorddetail);
And most relevantly for your case, loop over them:
foreach ( $xml->result->recorddetail as $recorddetail ) {
$product_id = $recorddetail->FL[0];
}
As a final tip, you probably want the $product_id variable to hold an ordinary string, not a SimpleXML object; you get that with a "string cast", like this:
$product_id = (string)$recorddetail->FL[0];

Related

wordpress shortcode is picking full XML instead of a single line

I am trying to create a wordpress shortcode which returns the price of a book from an API.
Ideally, I would like to be able to create a shortcode with this format [currency_isbn13] but for the moment I'd be happy to just create a fixed shortcode for each book and currency.
After various attempts, I was able to put together the following php code, but it is not working as it should
function Price() {
$isbn13 = 9783899735215;
$url = 'https://api.bookdepository.com/search/lookup?isbn13='.$isbn13.'&clientId={redact}&authenticationKey={redact}&IP={redact}&currencies=GBP';
$sxml = simplexml_load_file($url);
print_r($sxml);
return $sxml->price;
}
add_shortcode('isbn13', 'Price');
I would expect the shortcode to return the price of the book, but I get the following:
How can I fix this? I'm sure it is very simple but can't figure it out
SimpleXMLElement Object ( [resultset] => SimpleXMLElement Object ( [status] => Success [results] => 1 [totalResults] => 1 [currentPage] => 1 [totalPages] => 1 ) [items] => SimpleXMLElement Object ( [item] => SimpleXMLElement Object ( [identifiers] => SimpleXMLElement Object ( [isbn13] => 9783899735215 ) [url] => https://www.bookdepository.com/Crocodile-Newts-Axel-Hernandez/9783899735215 [biblio] => SimpleXMLElement Object ( [title] => Crocodile Newts [format] => Hardback ) [availability] => Available - dispatched from the UK in 4 business days [pricing] => SimpleXMLElement Object ( [price] => SimpleXMLElement Object ( [#attributes] => Array ( [currency] => GBP ) [selling] => 50.27 ) ) [contributors] => SimpleXMLElement Object ( [contributor] => SimpleXMLElement Object ( [name] => Axel Hernandez [roleDescription] => By (author) [url] => https://www.bookdepository.com/author/Axel-Hernandez ) ) ) ) )
Looks as though you need to expand
return $sxml->price;
as your structure is more complex. Looks as though
return (string)$sxml->items->item->pricing->price->selling;
The cast to (string) makes the value easier to use elsewhere.

PHP - Changing an Object for Consistency

I have a scenario where an API is returning multiple records inside object containing a numeric array like so;
stdClass Object
(
[Event] => Array
(
[0] => stdClass Object
(
[ID] => 111
[Name] => My First Event
[EventType] => stdClass Object
(
[ID] => 1
[Category] => Music
)
)
[1] => stdClass Object
(
[ID] => 222
[Name] => My Second Event
[EventType] => stdClass Object
(
[ID] => 2
[Category] => Sport
)
)
)
[Errors] => stdClass Object
(
[Result] => 0
[Message] =>
)
[RecordCount] => 2
)
I'm current using a foreach loop to iterate through the records. This works fine.
foreach($result->Event as $Event)
But there is a problem here I have a scenario where a single results is returned in the object like so;
stdClass Object
(
[Event] => stdClass Object
(
[ID] => 11
[Name] => My Only Event
[EventType] => stdClass Object
(
[ID] => 2
[Category] => Sport
)
)
[Errors] => stdClass Object
(
[Result] => 0
[Message] =>
)
[RecordCount] => 1
)
Notice there is no [0] array index for the single results.
What's the best way to overcome this keeping in mind that I have no control of the data returned by the API?
Check if Event is an array or an object
if( is_object( $result->Event ) )
{
// ...
}
else
{
foreach( // [....]
}
You may process the object or overwrite it with a 1 item array as suggested by Sam
Btw: very bad API design. I would complain....
The best workaround I have found is to add the single Event to an array with a zero index within the result object. This way the result object matches the same structure as a result containing multiple records.
if(!is_array($result->Event)){
$result->Event = array($result->Event);
}

Trying to extract an xml file stored as a blob from a database and storing the extracted xml data in a php object

I currently have a database which contains xml files stored as blobs. When I attempt to extract this data using sql I am not getting the data in the original xml format rather just bits of text from the xml file. I have tried a number of ways but no luck so far anyone have any ideas on how to do this?
The aim is to determine which xml file is needed for comparison, to retrieve it from the database and compare it to another xml file.
Heres one thing I've been trying:
**//************THIS IS WHERE THE PROBLEM IS*************************
if($databaseMatchedModelsObjects[$count] -> version == $maxVersion && $databaseMatchedModelsObjects[$count] -> release == $maxRelease){
$con2 = connect2();
$contentModel = $con2->prepare("SELECT fileName, type, size, content FROM model WHERE id=:id LIMIT 1");
//print_r($databaseMatchedModelsObjects[$count] -> mid);
$contentModel->bindParam('id',$databaseMatchedModelsObjects[$count] -> mid,PDO::PARAM_INT);
$contentModel->execute(array('id'=>$databaseMatchedModelsObjects[$count] -> mid));
$row = $contentModel->fetch();
//$sql_statement= "SELECT xmltype(content, nls_charset_id('CHAR_CS')).getclobval() rfile FROM model WHERE id =" . $databaseMatchedModelsObjects[$count] -> id;
//$sql_result = mysqli_query($con, $sql_prim);
//print_r($sql_result);
//if($row = #mysqli_fetch_array($result)) {
if($row) {
$finalModelToCompareTo = $row['content'];
//echo(simplexml_load_string());
//print_r(simplexml_load_string($finalModelToCompareTo));
//print_r($finalModelToCompareTo);
//$finalModelToCompareTo = $databaseMatchedModelsObjects[$count] -> content;
//print_r($databaseMatchedModelsObjects[$count] -> content);
}
}
Example print out using var dump of the content, just a snippet full print out is too long. This should be in xml format.
string(15513) " G title sub title 0 English 0 date This is the top level of the Common Information Model. This model contains the singleton, root Managed Object Class (MOC) ManagedElement under which the complete model is contained. Directly under ManagedElement are managed-function level classes SF, T, E and the root MOC of any managed functions. The Equipment Root MOC is in the Equipment Managed Object Model (MOM). The root MOC for a managed function is hosted in the managed function MOM. Deprecated, Contains product information for a Managed Element and ManagedFunction(s). Replaced by ProductData The product number in ABC format. For information, refer to Corporate Basic Standards. The product revision in the form R[1-9][A-Z]. For information, refer to Corporate Basic Standards. Common product name.
XML File that I will be comparing against Sample code:
How it is printed in comparison:
$uploaded_model = #simplexml_load_file($targetdir . "\\" . $fileinfo->getFilename()); print_r($uploaded_model);
SimpleXMLElement Object ( [dtdVersion] => G [momMetaData] => SimpleXMLElement Object ( [momTitle] => title [momSubTitle] => sub title [momIdentity] => SimpleXMLElement Object ( [docNum] => 0 [docLang] => English [docRev] => 0 [docDate] => date ) [createdBy] => SimpleXMLElement Object ( [signature] => xqichen ) ) [mim] => SimpleXMLElement Object ( [#attributes] => Array ( [author] => XQHE [contact] => ok#dektech.com.au [correction] => 0 [date] => 2014-11-22 [docNo] => [name] => CmwPm [namespace] => urn:com:CmwPm [namespacePrefix] => cmwpm [organization] => XDT/DEK [release] => 2 [revision] => A [version] => 2 ) [description] => Performance Management MOM. 3GPP defines Performance Management in 3GPP 32.401. [domainExtension] => SimpleXMLElement Object ( [#attributes] => Array ( [domain] => ECIM ) [extension] => Array ( [0] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => MomName [value] => PM ) ) [1] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => Version [value] => 2 ) ) [2] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => ecimMomRelease [value] => 3 ) ) [3]
=> SimpleXMLElement Object ( [#attributes] => Array ( [name] => ecimMomCorrection [value] => 0 ) ) [4] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => immNamespace [value] => MOM_NAME ) ) ) ) [implements] => SimpleXMLElement Object ( [#attributes] => Array ( [correction] => 0 [name] => ECIM_PM [release] => 3 [version] => 2 ) ) [struct] => Array ( [0] => SimpleXMLElement Object ( [#attributes]
=> Array ( [name] => MeasurementReaderNameValue ) [description] => This name value is used for real-time monitoring. The real-time monitoring is set up using a PM job of type REALTIMEJOB. [structMember] => Array ( [0] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => currentValue ) [description] => Contains the real-time value of the measurement. This value can be read in conjunction with attribute lastUpdated to determine the value of counters in real time. [string] => SimpleXMLElement Object ( ) ) [1] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => lastUpdated ) [description] => Contains the exact time the currentValue was last set. This attribute is used to determine how recent the value supplied in currentValue is. [derivedDataTypeRef] => SimpleXMLElement Object ( [#attributes] => Array ( [name] => DateTime ) [mimName] => CmwPm ) )
I managed to fix my problem by:
$xml = simplexml_load_string($finalModelToCompareTo);
The XML seems to have been converted to string within the blob and you need to use this method to convert it back to a SimpleXMLObject again.
I think it really IS a XML file. The string(15513) " G title sub title 0 En... representation is the same XML file parsed by the browser and you only see the plaintext values but not the XML tags. So, don't worry about the losses you see in the printout. If you open up the webpage source using Ctrl+U you can see the complete XML file syntax.

How to display a value from a SimpleXML object (the array notation is confusing me)

I have a PHP file that uses cURL to retrieve some XML. I now want to retrieve a value from the XML but I cannot traverse to it as I am confused with the notation.
Here's my retrieved XML:
SimpleXMLElement Object
(
[#attributes] => Array
(
[uri] => /fruit/apple/xml/green/pipType
)
[result] => SimpleXMLElement Object
(
[JobOpenings] => SimpleXMLElement Object
(
[row] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[no] => 1
)
[FL] => Array
(
[0] => 308343000000092052
[1] => ZR_6_JOB
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[no] => 2
)
[FL] => Array
(
[0] => 308343000000091031
[1] => ZR_5_JOB
)
)
)
)
)
)
I have this XML stored in a variable called $xml using:
$xml = new SimpleXmlElement($data, LIBXML_NOCDATA);
Any help for how I can select the ZR_5_JOB element please?
I have tried countless times, the last effort I had was:
print_r($xml->result->JobOpenings->row[0]->FL[0]);
Could anybody please help?
(I know I will then need to do some iteration, but I'll deal with that later!)
First loop the JobOpenings rows to get each row separately and then you can access the childrens of that element in an easy way.
foreach($xml->result->JobOpenings->row as $item) {
echo $item->FL[0] . '<br>';
}

How do I add/remove an entry to an array of objects?

I have an array that's made up of data returned by a SQL query:
$_SESSION['licensed_users'] = $db->get_results("SELECT np.id FROM `new_people` np LEFT JOIN institute.users_roles ur ON np.institute_uid = ur.uid WHERE np.company_id=$company_id AND ur.rid=8 AND np.active = 1");
This returns an array that looks like this:
Array (
[0] => stdClass Object ( [id] => 25590 )
[1] => stdClass Object ( [id] => 40657 )
[2] => stdClass Object ( [id] => 60685 )
[3] => stdClass Object ( [id] => 61900 )
[4] => stdClass Object ( [id] => 65224 )
[5] => stdClass Object ( [id] => 65369 )
[6] => stdClass Object ( [id] => 79171 )
[7] => stdClass Object ( [id] => 80763 )
[8] => stdClass Object ( [id] => 80762 )
[9] => stdClass Object ( [id] => 80761 )
)
In another section of the code I loop through the values to see if the current user is part of that array:
foreach($_SESSION'licensed_users'] as $key=>$value) {
if($value->id == $people_id) {
$is_licensed = true;
}
}
$is_licensed is used to determine which set of form fields to display to the user. When the user submits the form, if a certain group of fields is set to a certain value, I need to either add the user ($people_id) to the $_SESSION['licensed_users'] array if $is_licensed is false, or remove them from the array if $is_licensed is true. The code for determining which action to take is no problem; I just can't for the life of me remember/figure out how to add to an array of objects. I've seen this and this, but I already know if the ID is in the array or not; I just need to be able to add or remove it.
(Yes, there is a reason we're using session variables - we need to be able to pass values between pages of the site. It's either that or cookies.)
I've tried $_SESSION['licensed_users'][] = array("id"=>$people_id); but it doesn't seem to actually do anything.
To remove $lu[6]:
unset($lu[6]);
To add an element:
$lu[] = $current_user;

Categories