Pull values from SimpleXMLElement Object - php

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.

Related

In PHP how can I read subvalue of an XML line? [duplicate]

Sorry if this seems like an easy question, but I've started pulling hair out on this...
I have a XML file which looks like this...
<VAR VarNum="90">
<option>1</option>
</VAR>
I'm trying to get the VarNum.
So far I've been successful using the follow code to get the other information:
$xml=simplexml_load_file($file);
$option=$xml->option;
I just can't get VarNum (the attribute value I think?)
Thanks!
You should be able to get this using SimpleXMLElement::attributes()
Try this:
$xml=simplexml_load_file($file);
foreach($xml->Var[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
That will show you all the name/value attributes for the first foo element. It's an associative array, so you can do this as well:
$attr = $xml->Var[0]->attributes();
echo $attr['VarNum'];
What about using $xml['VarNum'] ?
Like this :
$str = <<<XML
<VAR VarNum="90">
<option>1</option>
</VAR>
XML;
$xml=simplexml_load_string($str);
$option=$xml->option;
var_dump((string)$xml['VarNum']);
(I've used simplexml_load_string because I've pasted your XML into a string, instead of creating a file ; what you are doing with simplexml_load_file is fine, in your case !)
Will get you
string '90' (length=2)
With simpleXML, you access attributes with an array syntax.
And you have to cast to a string to get the value, and not and instance of SimpleXMLElement
For instance, see example #5 of Basic usage in the manual :-)
[0] => Array
(
[#attributes] => Array
(
[uri] => https://abcd.com:1234/abc/cst/2/
[id] => 2
)
[name] => Array
(
[first] => abcd
[last] => efg
)
[company] => abc SOLUTION
[email] => abc#xyz.com
[homepage] => WWW.abcxyz.COM
[phone_numbers] => Array
(
[phone_number] => Array
(
[0] => Array
(
[main] => true
[type] => work
[list_order] => 1
[number] => +919876543210
)
[1] => Array
(
[main] => false
[type] => mobile
[list_order] => 2
[number] => +919876543210
)
)
)
[photo] => Array
(
[#attributes] => Array
(
[uri] => https://abcd.com:1234/abc/cst/2/cust_photo/
)
)
)
I applied the below code
$xml = simplexml_load_string($response);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
print_r($array);
but it is not use full i want all the data in single array in php
Try this
$xml->attributes()['YourPropertyName']; //check property case also

getting elemints out of simpleXML Array

I am trying to get elements out of a simpleXML array and for some reason I am unable to call them.
Here is the array.
Array
(
[0] => SimpleXMLElement Object
(
[NameChangeIndicator] => N
[NameChangeDate] => SimpleXMLElement Object
(
)
[PreviousName] => SimpleXMLElement Object
(
)
[Score] => 53
[NumberOfSubs] => SimpleXMLElement Object
(
)
[NumberOfJU] => SimpleXMLElement Object
(
)
[DateLastJU] => SimpleXMLElement Object
(
)
[NumberActPrincipals] => 1
[NumberActPrincipalsJU] => SimpleXMLElement Object
(
)
[LastestBankCode] => SimpleXMLElement Object
(
)
[LastestBankCodeDate] => SimpleXMLElement Object
(
)
[NumberRDs] => SimpleXMLElement Object
(
)
[LiqIndicator] => SimpleXMLElement Object
(
)
[TotEnqLast12Mth] => SimpleXMLElement Object
(
)
[TotEnqLast3Mth] => SimpleXMLElement Object
(
)
[RefsNoOfReferences] => SimpleXMLElement Object
(
)
[RefsHighMthPurchases] => SimpleXMLElement Object
(
)
[RefsHighMthPurchasesTermGiven] => SimpleXMLElement Object
(
)
[RefsHighMthPurchasesTermTaken] => SimpleXMLElement Object
(
)
[RefsLowMthPurchases] => SimpleXMLElement Object
(
)
[RefsLowMthPurchasesTermGiven] => SimpleXMLElement Object
(
)
[RefsLowMthPurchasesTermTaken] => SimpleXMLElement Object
(
)
[KissNoOfSuppliers] => SimpleXMLElement Object
(
)
[KissNoOfODSuppliers] => SimpleXMLElement Object
(
)
[KissAmountOS] => SimpleXMLElement Object
(
)
[KissAmountOD] => SimpleXMLElement Object
(
)
[KissPercntage] => SimpleXMLElement Object
(
)
[LatestBankCodeDesc] => SimpleXMLElement Object
(
)
[HoldingCmpName] => SimpleXMLElement Object
(
)
)
)
So I am doing the following call to get the array.
$new_str = htmlspecialchars_decode($str);
$new_str = str_replace('<?xml version="1.0" encoding="UTF-8"?>','',$new_str);
$xml = simplexml_load_string($new_str);
$dom = new SimpleXMLElement($new_str);
$xml_array = $dom->xpath("//*[name()='ReportSummary']");
echo "{$xml_array[0]['Score']}";
But I am unable to pull the object out of the Array. I am not sure if the array
is being correctly sent back to me due to the fact that if I don't decode the string I don't get a array back. The weird thing is that in the array I keep on seeing "SimpleXMLElement Object" and I am not sure if that is correct.
Any help will be appreciated.
As the dump output says, SimpleXML is a type of object, not a way of creating arrays.
These two lines are different ways of writing the same thing, you only need one of them; in either case you end up with a SimpleXMLElement object:
$xml = simplexml_load_string($new_str);
$xml = new SimpleXMLElement($new_str);
The outer array you are seeing is to hold the results of the XPath query, since they can come from anywhere in the XML tree. It is an array of SimpleXMLElement objects.
For how to access data using SimpleXML, see the basic usage page in the PHP manual.
In your case, Score is an element of the document, so needs to be accessed with the $node->property syntax.
Here's a tidied up version of your code:
$new_str = htmlspecialchars_decode($str);
// Are you sure the next line is necessary? That looks like a valid XML opening to me.
$new_str = str_replace('<?xml version="1.0" encoding="UTF-8"?>','',$new_str);
$xml = simplexml_load_string($new_str);
// I think this simpler XPath expression means the same as yours, but I might be wrong
$xpath_results = $xml->xpath('//ReportSummary');
// Beware that the XPath could return no matches, in which case the following
// would give an error. Best to check count($xpath_results) > 0 first.
echo $xpath_results[0]->Score;
To IMSoP: thanks for the help but I had to modify it a bit:
$dom = new SimpleXMLElement($new_str);
$xml_array = $dom->xpath("//*[name()='ReportSummary']");
echo $xml_array[0]->Score;
And from that I got the correct result, thanks a lot!

How to read XML output using PHP

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.

How can i access simplexml elements from this list?

So i have these simplexmlelement objects. And i cant get it to work how to parse a specific element.
SimpleXMLElement Object
(
[Generation] => SimpleXMLElement Object
(
[#attributes] => Array
(
[version] => 3.1.0-alpha3
[timestamp] => 1355434832
)
)
[Options] => SimpleXMLElement Object
(
[#attributes] => Array
(
[tempFormat] => c
[byteFormat] => auto_binary
[refresh] => 60000
[showPickListTemplate] => true
[showPickListLang] => true
)
)
[UsedPlugins] => SimpleXMLElement Object
(
)
[Vitals] => SimpleXMLElement Object
(
[#attributes] => Array
(
[Hostname] => domain.tld
[IPAddr] => 127.0.0.1
[Kernel] => 2.6.32-11-pve (SMP) x86_64
[Distro] => Ubuntu 12.04.1 LTS
[Distroicon] => Ubuntu.png
[Uptime] => 1993669.51
[Users] => 1
[LoadAvg] => 0.08 0.02 0.01
[CPULoad] => 0
)
)
....etc...
)
I have made something like this to access the Hostname for example:
echo $xml->Generation->Vitals[0]->Hostname;
But i think i am doing something wrong. Could someone point me in the right direction?
It would just be:
$xml->Vitals[0]->attributes()->Hostname
I am not entirely sure if you have to stick with a SimpleXml object, but if you don't, have a look at the DOMDocument and DOMXPath combination. I really like it. Just to be clear, it's hard to get into, but as soon as you get the hang of it, you are going to like it.
You can just do something like this:
$doc = new DOMDocument();
$doc->load('http://www.example.com/file.xml');
$xpath = new DOMXPath($doc);
$result = $xpath->query('//Vitals');
// print them all
foreach ($result as $r){
echo $r->getAttribute('Hostname'); //your desired value
}
// or just the first one
echo $result->item(0)->getAttribute('Hostname');
You could also make the query slightly bigger to get the attribute right away like so: //Vitals#Hostname which should work as well.
And with this start you will possibly get the hang of it.
Further reading:
http://php.net/manual/en/class.domdocument.php
http://php.net/manual/en/class.domxpath.php
http://php.net/manual/en/domxpath.query.php
http://www.tizag.com/xmlTutorial/xpathattribute.php
http://www.w3schools.com/xpath/xpath_syntax.asp

Get Methods from REST call

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.

Categories