How can I properly parse a SimpleXML Object in PHP? - php

I'm using the CloudFusion class to get Amazon.com data and my code is simple:
$items = $pas->item_search( "shoes", array(
"ResponseGroup" => "Small",
"SearchIndex" => "Blended" ));
$items = $items->body->Items;
echo "<pre>";
print_r( $items );
echo "</pre>";
This returns the following:
SimpleXMLElement Object (
[Request] => SimpleXMLElement Object
(
[IsValid] => True
[ItemSearchRequest] => SimpleXMLElement Object
(
[Keywords] => shoes
[ResponseGroup] => Small
[SearchIndex] => Blended
)
)
[TotalResults] => 737435
[TotalPages] => 245816
[SearchResultsMap] => SimpleXMLElement Object
(
[SearchIndex] => Array
(
[0] => SimpleXMLElement Object
(
[IndexName] => Kitchen
....
)
[Item] => Array
(
[0] => SimpleXMLElement Object
(
[ASIN] => B0001Z95QY
[DetailPageURL] => http://www.amazon.com/Household-Essentials-MS6030-Seasonal-Storage/dp/B0001Z95QY%3FSubscriptionId%3D0WASFFPR5B82TH4ZQB82%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB0001Z95QY
[ItemLinks] => SimpleXMLElement Object
(
[ItemLink] => Array
(
[0] => SimpleXMLElement Object
(
[Description] => Technical Details
[URL] => http://www.amazon.com/Household-Essentials-MS6030-Seasonal-Storage/dp/tech-data/B0001Z95QY%3FSubscriptionId%3D0WASFFPR5B82TH4ZQB82%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D386001%26creativeASIN%3DB0001Z95QY
) ....................
)
[1] => SimpleXMLElement Object
(
[ASIN] => B001ACNBZ8
[DetailPageURL] => http://www.amazon.com/Peet-Shoe-Dryer-Boot-Original/dp/B001ACNBZ8%3FSubscriptionId%3D0WASFFPR5B82TH4ZQB82%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB001ACNBZ8
[ItemLinks] => SimpleXMLElement Object
(...................
)
)
What I'd like to do is get down to the "Item" level, then run a foreach to get each individual entry. I tried $items = $items->Item, but this returns only the first entry.
Any ideas?

First of all, you should avoid using print_r() on SimpleXMLElement, instead just take a look at the XML using asXML(). That's also what you should post here, instead of print_r()'s output.
I can't decipher the code you have posted so I'll take a wild guess and suggest that you try something like:
foreach ($items->body->Items->Item as $Item)
{
}
At any rate, if you want to iterate over something, foreach is the answer.

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.

Getting objects instead of object properties in array

When I set $sales like so $sales = $response->xml->transactions the contents look like:
SimpleXMLElement Object
(
[transaction] => Array
(
[0] => SimpleXMLElement Object
(
[transId] => 9999999999
[submitTimeUTC] => 2016-03-16T21:57:54Z
[submitTimeLocal] => 2016-03-16T14:57:54
[transactionStatus] => capturedPendingSettlement
[invoiceNumber] => 4b1008a87f5262f0c867
[firstName] => Foo
[lastName] => Bar
[accountType] => Visa
[accountNumber] => XXXX1414
[settleAmount] => 155.00
[marketType] => eCommerce
[product] => Card Not Present
)
[1] => SimpleXMLElement Object
(
[transId] =>
So ->transaction contains an array. But if I do this:
$sales = $response->xml->transactions->transaction;
foreach ($sales as $s) {
$list[]= $s->invoiceNumber;
}
$list contains
Array
(
[0] => SimpleXMLElement Object
(
[0] => ac502c094fe1722ba100
)
[1] => SimpleXMLElement Object
(
[0] => e2eb58351c87155e3720
)
[2] => SimpleXMLElement Object
(
[0] => 0bca2bb6d5a13e641b67
)
What am I doing wrong? Where are the SimpleXMLElement Objects coming from where I just expected the invoiceNumber string?
The reason you are getting the SimpleXMLElement type objects is because when you are doing $list[]= $s->invoiceNumber; you are adding the element as it is. Since it is part of the SimpleXMLElement object it has that type internally. This comes up a lot when working with SimpleXML so its good to keep in mind.
As mentioned in the comments casting to a string will give you just the value:
$list[] = (string) $s->invoiceNumber;

PHP - How to read data from SOAP XML

I have code for read XML SOAP 1.2 from web service.
Im using this: https://stackoverflow.com/a/18580428/2629513
I get this code below:
SimpleXMLElement Object
(
[OdkazyResponse] => SimpleXMLElement Object
(
[OdkazyResult] => SimpleXMLElement Object
(
[odkazy] => SimpleXMLElement Object
(
[odkaz] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[kod_zbozi] => 31400001
[typ] => OBR1
[popis] => Oki ML 280 - foto
[url] => http://www.atcomp.cz/katalog/31400001/ML280.gif
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[kod_zbozi] => EC376123GB
[typ] => OBR1
[popis] => Malý obrázek
[url] => http://www.atcomp.cz/katalog/EC376123GB/lq-680_-_maly.jpg
)
)
[2] => SimpleXMLElement Object
(
[#attributes] => Array
(
[kod_zbozi] => EC376123GB
[typ] => OBR2
[popis] => Velký obrázek
[url] => http://www.atcomp.cz/katalog/EC376123GB/lq-680_-_velky.jpg
)
)
And how I can read the [kod_zbozi], [typ], [popis], [url] attributes? I need to save it into my mysql database (this is not problem, the problem is read the data from this format XML). Thanks.
Well, the very first thing you might want to do is to convert that object into an array (to avoid naming problems)
You can use this function to do that:
function object2array($object) {
return json_decode(json_encode($object), true);
}
then something like this:
$data = object2array(simplexml_load_string('....'));
print_r($data); // Its regular array now, use it keys to access values, then simply insert them into db

SimpleXMLElement parsing issue with PHP

I'm trying to parse out the following response:
SimpleXMLElement Object (
[responseType] => SimpleXMLElement Object (
[inputConceptName] => aspirin [inputKindName] => % )
[groupConcepts] => SimpleXMLElement Object (
[concept] => Array (
[0] => SimpleXMLElement Object (
[conceptName] => ASPIRIN
[conceptNui] => N0000145918
[conceptKind] => DRUG_KIND )
[1] => SimpleXMLElement Object ( #
[conceptName] => Aspirin
[conceptNui] => N0000006582
[conceptKind] => INGREDIENT_KIND )
) ) )
in PHP. I have it stored as a curl string:
$xml = simplexml_load_string($data);
print_r($xml);
How do I get just the conceptNui of the first object as a PHP variable?
Take a look at the documentation, it give simple example to understand the friendly syntax to extract the data :
http://www.php.net/manual/en/simplexml.examples-basic.php
In your case, it could be :
$xml->groupConcepts->concept[0]->conceptNui
As your structure is
SimpleXMLElement Object (
[responseType] => SimpleXMLElement Object (
[inputConceptName] => aspirin
[inputKindName] => % )
[groupConcepts] => SimpleXMLElement Object (
[concept] => Array ([0] => SimpleXMLElement Object (
[conceptName] => ASPIRIN
[conceptNui] => N0000145918
[conceptKind] => DRUG_KIND )
[1] => SimpleXMLElement Object (
[conceptName] => Aspirin
[conceptNui] => N0000006582
[conceptKind] => INGREDIENT_KIND )
)
)
)
$conceptNui = $mainObj->groupConcepts->concept[0]->conceptNui;

I'm trying to find an attribute using simpleXML

I have a simpleXML output of:
SimpleXMLElement Object
(
[#attributes] => Array
(
[version] => 2
)
[currentTime] => 2013-02-05 21:26:09
[result] => SimpleXMLElement Object
(
[rowset] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => characters
[key] => characterID
[columns] => name,characterID,corporationName,corporationID
)
[row] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => Wrytha Cy
[characterID] => 209668693
[corporationName] => Deep Core Mining Inc.
[corporationID] => 1000006
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => Eve Mae
[characterID] => 624980803
[corporationName] => Viziam
[corporationID] => 1000066
)
)
[2] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => Wrytha
[characterID] => 709227913
[corporationName] => The Flying Tigers
[corporationID] => 669350666
)
)
)
)
)
[cachedUntil] => 2013-02-05 21:35:04
)
I would like to loop through with my php loop and get "name' and "characterID". I've trying something like:
$simpleXML = simplexml_load_string($xml);
foreach ($simpleXML->result->rowset->row as $row) {
print_r($row);
$name = $row['#attributes']['name'];
echo $name.'<br>';
}
but $name is not being set. It's gonna be something simple, just not seeing it in my haste and first time with simpleXML.
Attributes are accessed using the syntax $element['attribute_name'], so in your case, you need $row['name'].
It's important to remember that SimpleXML objects are kind of magic - the $element->child, $element_list[0] and $element['foo'] syntax overloads the normal PHP logic to be useful. Similarly, (string)$element will give you the full textual content of an element, however it is broken up in the actual XML.
As such, the print_r output will not give you a "real" view of the object, so should be used with care. There are a couple of alternative debug functions I've written here which give a more accurate idea of how the object will behave.

Categories