I am trying to read an XML output listed below:
SimpleXMLElement Object
(
[merchant] => SimpleXMLElement Object
(
[merchant-id] => SimpleXMLElement Object
(
)
[merchant-name] => Snip-Its
[merchant-category] => Hair
[merchant-website] => www.snipits.com
)
[store] => SimpleXMLElement Object
(
[store-id] => 173DFBB7-67F6-DE11-AD5B-0026B953348A
[store-name] => Heb
[store-number] => 0109
)
[coupon] => SimpleXMLElement Object
(
[coupon-id] => 385748
[coupon-address] => 14096 Memorial Drive
[coupon-city] => Houston
[coupon-state] => TX
)
)
using PHP script as follows but I get a value of '0':
foreach( $data->coupons as $mycoupon ) {
$address = $mycoupon->coupon->coupon-address;
//print_r($mycoupon);
}
So, please help me to understand how to read the values of SimpleXMLElement Object and assign them to a local variable.
There are certain characters that are not permitted for PHP's naming convention such as a hyphen. To deal with this just enclose the element name in braces as a string as such:
$address = $mycoupon->coupon->{'coupon-address'};
Give that a try.
Related
I'm using the namecheap API to do some stuff, it's the first time I've used a API and I'm running into a bit of a problem.
This is what I have so far:
$ApiKey = "**********************";
$ApiUser = "*****";
$UserName = "*********";
$ClientIP = "********";
$NamecheapURI = "https://api.namecheap.com/xml.response";
$executionURL = $NamecheapURI."?ApiUser=".$ApiUser."&ApiKey=".$ApiKey."&UserName=".$UserName."&Command=namecheap.domains.check&ClientIp=".$ClientIP."&DomainList=".$domain;
$xml = simplexml_load_file($executionURL);
print_r($xml);
When print $xml I am returned simple XML objects:
SimpleXMLElement Object
(
[#attributes] => Array
(
[Status] => OK
)
[Errors] => SimpleXMLElement Object
(
)
[Warnings] => SimpleXMLElement Object
(
)
[RequestedCommand] => namecheap.domains.check
[CommandResponse] => SimpleXMLElement Object
(
[#attributes] => Array
(
[Type] => namecheap.domains.check
)
[DomainCheckResult] => SimpleXMLElement Object
(
[#attributes] => Array
(
[Domain] => facebook.com
[Available] => false
[ErrorNo] => 0
[Description] =>
[IsPremiumName] => false
[PremiumRegistrationPrice] => 0
[PremiumRenewalPrice] => 0
[PremiumRestorePrice] => 0
[PremiumTransferPrice] => 0
[IcannFee] => 0
[EapFee] => 0
)
)
)
[Server] => PHX01APIEXT03
[GMTTimeDifference] => --5:00
[ExecutionTime] => 0.008
)
My question is beyond this, how do I move forward and pull data from this?
I've tried treating this as an array but I am getting nowhere, when using is_array() to test if it was an array it says it's not which I don't understand...
I apologise if this is a noob question, I am a bit new to this. In short, what do I need to do to pull data from this?
Thanks in advance!
Learning to use SimpleXML is much better than trying to convert it to arrays/json/anything else and simple (hence the name). A quick example...
$response = '<?xml version="1.0" encoding="UTF-8"?>
<CommandResponse Type="namecheap.domains.check">
<DomainCheckResult Domain="facebook.com">
<Element>1234</Element>
<Element>12345</Element>
</DomainCheckResult>
</CommandResponse>';
$xml = simplexml_load_string($response);
echo "DOmain=".$xml->DomainCheckResult['Domain'].PHP_EOL;
foreach ( $xml->DomainCheckResult->Element as $value) {
echo "Value=".(string)$value.PHP_EOL;
}
outputs...
DOmain=facebook.com
Value=1234
Value=12345
You have to adapt this to your own XML, but the idea is that if you want to access an element of an item you use object notation -> and if you need to get an attribute, use array notation [].
So in the above code, the first echo ($xml->DomainCheckResult['Domain']) gets the <DomainCheckResult> element and outputs the Domain attribute.
Then the foreach loop says fetch each <Element> within <DomainCheckResult> and output the value.
i wont to list a set of files in a directory and the files in its sub directory using a loop rather than the function
as im getting the information about the directory through an xml based webdav and php native functions are infertile so please understand the issue has not yet been lodged here
$urlloc is used to remove the same directory from being looped again
foreach ($xml as $key) {
if(empty($key->propstat->prop->resourcetype[0])){
echo $key->href."<br/>";//files are printed, for debugging perposes im printing it
}else{
$Nurlloc=$key->href;
if ($Nurlloc!=$urlloc){
echo "<b>".$Nurlloc."</b><br/>";//directorys printed in bold for debugging
$urlloc=$Nurlloc;
//gtndirdown()
above is the method im getting to know if its a directory or not
NOTE i want to be able to make this code loop through and get me all the files in the directory i will also post the array of files im getting
[response] => Array
(
[0] => SimpleXMLElement Object
(
[href] => /dav/product_images/
[propstat] => SimpleXMLElement Object
(
[prop] => SimpleXMLElement Object
(
[resourcetype] => SimpleXMLElement Object
(
[0] => SimpleXMLElement Object
(
)
)
[quota-used-bytes] => 2147483647
[quota-available-bytes] => 2147483647
)
[status] => HTTP/1.1 200 OK
)
)
[1] => SimpleXMLElement Object
(
[href] => /dav/product_images/a/
[propstat] => SimpleXMLElement Object
(
[prop] => SimpleXMLElement Object
(
[resourcetype] => SimpleXMLElement Object
(
[0] => SimpleXMLElement Object
(
)
)
[quota-used-bytes] => 2147483647
[quota-available-bytes] => 2147483647
)
[status] => HTTP/1.1 200 OK
)
)
iv been stuck in this issue for 4 days and i have would like if some one could come up with a logic for this issue
maybe this is an idea that you can implement in your logic
// the name of directory
$dir='path_to_your_directory';
$files = array_slice(scandir($dir), 2);
print_r($files);
I have a SOAP Response from a Web Service and have extracted the XML data as a SimpleXMLElement. I have then iterated through this object to extract the various fields I need and save them into an array, which becomes an array of SimpleXMLElement objects.
I am now trying to export this data into a MySQL Database which, according to my research, means turning the array into a String and then using mysql_query("INSERT INTO (whatever) VALUES (whatever)");. I have tried implode and serialize but neither work and I get the error:
Fatal error: Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed'
This is what the array I have created from the SimpleXMLELement looks like:
Array
(
[0] => Array
(
[uid] => SimpleXMLElement Object
(
[0] => WOS:000238186400009
)
[journal] => SimpleXMLElement Object
(
[#attributes] => Array
(
[type] => source
)
)
[publication] => SimpleXMLElement Object
(
[#attributes] => Array
(
[type] => item
)
[0] => Abundance of hedgehogs (Erinaceus europaeus) in relation to the density and distribution of badgers (Meles meles)
)
[year] => 2006
[author1] => SimpleXMLElement Object
(
[0] => Young, RP
)
[address] => SimpleXMLElement Object
(
[0] => Cent Sci Lab, Sand Hutton, Yorks, England
)
[author2] => SimpleXMLElement Object
(
[0] => Davison, J
)
[author3] => SimpleXMLElement Object
(
[0] => Trewby, ID
)
[citations] => SimpleXMLElement Object
(
[#attributes] => Array
(
[local_count] => 15
[coll_id] => WOS
)
)
) ... etc ...
)
Can anyone help me with the method to get this data into my database, please? Do I need to change it into (yet) another format?
You have to iterate through your array to create a new array fulfilled with strings instead of SimpleXMLElement, such as :
<?php
// your array (already built)
$arraySimpleXml = array(
"example1" => new SimpleXMLElement("<test>value</test>"),
"example2" => new SimpleXMLElement("<test>value2</test>")
);
// output array, to store in database
$result = array();
foreach($arraySimpleXml as $key => $simpleXml) {
$result[$key] = $simpleXml->asXML();
}
// gets your result as a string => you can now insert it into mysql
$dbInsertion = serialize($result);
?>
So I worked out how to change the data into a standard array rather than an array of SimpleXMLElements so that I can successfully insert it into a MySQL database.
When iterating the SimpleXMLElement object to extract the data I needed I cast the type as String so that now my array has the format (as opposed to above):
Array
(
[0] => Array
(
[uid] => WOS:000238186400009
[journal] => JOURNAL OF ZOOLOGY
[publication] => Abundance of hedgehogs (Erinaceus europaeus) in relation to the density and distribution of badgers (Meles meles)
[year] => 2006
[author1] => Young, RP
[address] => Cent Sci Lab, Sand Hutton, Yorks, England
[author2] => Davison, J
[author3] => Trewby, ID
[citations] => 15
)
)
Thought I'd post this in case anyone has a similar problem in future. To do this, when iterating the data instead of:
$uid = $record->UID;
I did:
$uid = (string)$record->UID;
For each of the data fields I required. This ensures the data is stored as a String and so removes the SimpleXMLElement format.
I would like to get methods from REST XML file via PHP.
I have local REST file, which is in this format:
SimpleXMLElement Object
(
[doc] => SimpleXMLElement Object
(
)
[resources] => SimpleXMLElement Object
(
[#attributes] => Array
(
[base] => https://**url**
)
[resource] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[path] => xml/{accesskey}/project
)
[param] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => accesskey
[style] => template
[type] => xs:string
)
)
[method] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => getAllProjects
[name] => GET
)
[response] => SimpleXMLElement Object
(
[representation] => SimpleXMLElement Object
(
[#attributes] => Array
(
[mediaType] => application/xml; charset=utf-8
)
)
)
)
... and so on
I have the following code, but it returns just the first method name:
$file="application.wadl";
$xml = simplexml_load_file($file);
foreach($xml->resources[0]->resource->method->attributes() as $a => $b) {
echo $b,"\n";
}
I would like to extract all of them, not just the first one. How to do that?
Rather than looping over the attributes of one element, you need to loop over all the elements with the same name. Due to the magic of SimpleXML, this is as simple as this:
foreach($xml->resources->resource->method as $method) {
echo $method['id'],"\n";
}
When followed immediately by another operator, as with ->resources, SimpleXML assumes you just want the first element with that name. But if you loop over, it will give you each of them, as a SimpleXML object.
EDIT : It looks like the nesting of your XML means you need some form of recursion (you need to look at $xml->resources->resource->resource->resource->method etc).
Something like this perhaps (untested example)?
function get_methods($base_url, $node)
{
$all_methods = array();
// Child resources: build up the path, and recursively fetch all methods
foreach ( $node->resource as $child_resource )
{
$child_url = $base_url . '/' . (string)$child_resource['path'];
$all_methods = array_merge(
$all_methods,
get_methods($child_url, $child_resource)
);
}
// Methods in this resource: add to array directly
foreach ( $node->method as $method )
{
$method_url = $base_url . '/' .(string)$method['id'];
$all_methods[$method_url] = (string)$method['id'];
}
return $all_methods;
}
print_r( get_methods('/', $xml->resources) );
Incidentally, print_r won't always give you the best view of a SimpleXML object, because they are actually wrappers around non-PHP code. Try this simplexml_dump() function instead.
I've seen similar questions on here but I can't seem to apply the solutions to my problem. I have a variable called $results which I got from an API. I'll change the proper nouns so as to protect my work's customers:
stdClass Object
(
[out] => stdClass Object
(
[count] => 2
[transactions] => stdClass Object
(
[RealTimeCommissionDataV2] => Array
(
[0] => stdClass Object
(
[adId] => 12345678
[advertiserId] => 123456789
[advertiserName] => Chuck E. Cheese, inc.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:44:25-08:00
[orderId] => X-XXXXXXXXXX
[saleAmount] => 0
[sid] => 123456789
[websiteId] => 2211944
)
[1] => stdClass Object
(
[adId] => 987654321
[advertiserId] => 12345
[advertiserName] => Chorizon Wireless.
[commissionAmount] => 50
[country] => US
[details] => stdClass Object
(
)
[eventDate] => 2009-11-16T09:58:40-08:00
[orderId] => X-CXXXXXX
[saleAmount] => 0
[sid] => 61-122112
[websiteId] => 1111922
)
)
)
)
)
I shortened it to two entries here but the number of entries will vary, it's the result of a check for transactions in the past hour, there may sometimes be only one and sometimes as many as a dozen.
I want to assign these entries to variables like websiteId1 websiteId2 etc. I know I need to do a foreach loop but can't seem to figure it out. How can I write it so that I get the "[details]" as well?
foreach ($results->out->transactions->RealTimeCommissionDataV2 AS $commissionData) {
// you can access the commissionData objects now, i.e.:
$commissionData->adId;
$commissionData->details;
}
<?
foreach ($result->out->transactions->RealTimeCommissionDataV2 as $item)
{
// do somthing with each item.
print_r($item);
// or the details array
$num_details = sizeof($item->details)
}
I think this is what you want.
EDIT
Updated based on some notes in the documentation. Specifically, these two
a numerically indexed array will not
produce results unless you use
EXTR_PREFIX_ALL or
EXTR_PREFIX_INVALID.
Prefixes are automatically separated
from the array key by an underscore
character.
echo extract( $results->out->transactions->RealTimeCommissionDataV2, EXTR_PREFIX_ALL, 'websiteId' );
// test the extract
print_r( $websiteId_0 );