Parse xml array in php [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Able to see a variable in print_r()'s output, but not sure how to access it in code
SimpleXMLElement Object
(
[Header] => SimpleXMLElement Object
(
)
[Body] => SimpleXMLElement Object
(
[CreateUserResponse] => SimpleXMLElement Object
(
[username] => anup_165
[password] => xnrrtgohgv
[result] => SimpleXMLElement Object
(
[succeeded] => true
[errorCode] => 0
[errorText] => SimpleXMLElement Object
(
)
)
)
)
)
i want to fetch username , password and succeeded from the above array

Do you mean:
$username = (string) $xml->Body["CreateUserResponse"]->username;
$password = (string) $xml->Body["CreateUserResponse"]->password;

Well i am going out on a limb here, but it might be something like:
$object['body']['CreateUserResponse']['username']
and
$object['body']['CreateUserResponse']['password']

//For Parsing the xml
$xmltoaparse=simplexml_load_string($xmlresponse);
foreach($xmltoaparse->children() as $iasorecord)
{
foreach($iasorecord as $iasouserrecord) //for each for machhnia attributes
{
foreach($iasouserrecord as $iasousersrecord) //for each for machhnia attributes
{
echo $iasousersrecord->getName();
echo $iasousersrecord;
}
}
}

Related

Pull values from SimpleXMLElement Object

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.

How to get a value from an array key within an stdClass Object [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 6 years ago.
I'm building a php webapp and I want to get a list of id's from an array named $array.
stdClass Object
(
[users] => Array
(
[0] => stdClass Object
(
[id] => 90379747
[id_str] => 90379747
)
[1] => stdClass Object
(
[id] => 30207605
[id_str] => 30207605
)
)
)
However when I try to get the value from the id key it somehow is not working.
echo "<h1>Result</h1>";
foreach ($array as $obj)
{
echo $obj->id;
}
What am I doing wrong here. Other examples on stackoverflow seem to suggest this should work.
You iterate an object, not an array. Try this way:
foreach ($array->users as $obj)
{
echo $obj->id;
}

PHP Loop stdClass Object [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 7 years ago.
I have a call to a webservice which is returning json data. I use:
$response_json = json_decode ( $response );
If I print_r($response) I get this:
stdClass Object
(
[meta] => stdClass Object
(
[no_of_pages] => 3
[current_page] => 1
[max_items_per_page] => 250
[no_of_items] => 740
)
[data] => Array
(
[0] => stdClass Object
(
[orderid] => 322191645
[customer] => stdClass Object
(
[city] => FELIXSTOWE
I am trying to loop through the orders:
foreach($response_json as $orders) {
echo $orders.['data'].[0].['orderid'];
}
but I keep getting:
Catchable fatal error: Object of class stdClass could not be converted to string. I have also tried many other ways, but I just can't seem to access the data in a loop. Thanks in advance.
You can json_decode as associative array.
$response = json_decode ($response, true);
foreach($response as $orders) {
echo $orders[0]['orderid'];
}
Don't use dots between brackets.
Skip "data" in your array.
Example:
foreach($response_json as $orders) {
echo $orders[0]['orderid'];
}

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!

Reading XML file - strange PHP object notation

I have a XML file simillar to this :
<information version="2">
<currentTime>2014-06-06 17:28:16</currentTime>
<result>
<name>Mark</name>
<surname>Smith</surname>
</result>
I read it with php function and parse it to the object with function, like this:
function parse_data($data){
$return_data['currentTime'] = $data->currentTime;
$return_data['name'] = $data->result->name;
$return_data['surname'] = $data->result->surname;
return $return_data;
}
$xml = simplexml_load_string(file_get_contents($link));
$object = parse_data($xml);
Then, when I echo it on the screen, to check how it look:
//json_encode($xml);
{
"#attributes":{"version":"2"},
"currentTime":"2014-06-06 17:28:16",
"result":{"name":"Mark","surname":"Smith"}
}
//print_r($xml);
SimpleXMLElement Object (
[#attributes] => Array ( [version] => 2 )
[currentTime] => 2014-06-06 17:56:30
[result] => SimpleXMLElement Object (
[name] => Mark
[surname] => Smith
)
)
//json_encode($object);
{
"currentTime":{"0":"2014-06-06 17:28:16"},
"name":{"0":"Mark"},
"surname":{"0":"Smith"}
}
//print_r($object);
Array (
[currentTime] => SimpleXMLElement Object ( [0] => 2014-06-06 17:52:50 )
[name] => SimpleXMLElement Object ( [0] => Mark)
[surname] => SimpleXMLElement Object ( [0] => Smith )
)
What is wrong with my code? He seems to read the informaton in xml file as array? Because of this strange notation I cannont operate on this data normally.
It also behave like this:
echo json_encode($object['name']); will give -> {"0":"Mark"}
echo $object['name']; will give -> Mark
Can anybody help me? What am I doing wrong?
I want my $object to look like this:
//json_encode($object);
{
"currentTime":"2014-06-06 17:28:16",
"name":"Mark",
"surname":"Smith"
}
Edit1: added print_r values
Yes, as you have noticed the type returned by $someSimpleXMLNode is an object. If you want the node value (as a string for example) use:
$return_data['currentTime'] = (string)$data->currentTime;
which is the same as doing
$return_data['currentTime'] = $data->currentTime->__toString();
etc
When you do
echo $data->currentTime;
the node is automatically coerced into a string (because echo only handles strings). This is done (generally, in php) by the object's __toString method.

Categories