XML to array, xml2ary bug - php

I am using this function http://mysrc.blogspot.it/2007/02/php-xml-to-array-and-backwards.html
to parse an XML to an Array. Very great function. But the strange thing is that
if I have the following 2 xml files:
<response>
<company prop1=1>
</company>
<company prop1=2>
</company>
</response>
<response>
<company prop1=1>
</company>
</response>
I got different result. For the first case, I got an array of two elements:
Array(
int(0) => _a => Array(...)
int(1) => _a => Array(...)
)
but for the second case I got
Array (
_a => Array(...)
)
which is not an array with indexes as the first case. This complicates parsing.
Does anybody have any idea how to modify the code?
Regards.

Let's say you do something like
$result = xml2ary($xml);
Try adding this line after your call to xml2ary():
$result = is_int(reset(array_keys($result))) ? $result : array($result);
This checks if the first key of the result array is an integer (which means that the xml2ary function returned multiple results. If not, it automatically wraps the $result variable in an array(), so that you have the same response format even when only one XML item is parsed.

Try using the PHP simplexml class:
http://php.net/manual/en/book.simplexml.php
It's the best way to parse XML with PHP

Related

Get Attribute value from Soap Response PHP

I am getting a soap response as expected and then converting to an array. Here is my code:
$response = $client->__getLastResponse();
$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = new SimpleXMLElement($response);
$body = $xml->xpath('//soapBody')[0];
$array = json_decode( str_replace('#', '', json_encode((array)$body)), TRUE);
print_r($array);
here is the output:
Array (
[GetCompanyCodeResponse] => Array (
[GetCompanyCodeResult] => Array (
[Customers] => Array (
[Customer] => Array (
[attributes] => Array (
[CustomerNo] => 103987
[CustomerName] => epds api testers Inc
[ContactId] => 219196
)
)
)
)
)
How do i echo the ContactId? Ive tried the following:
$att = $array->attributes();
$array->attributes()->{'ContactId'};
print_r($array);
I get the following error:
Fatal error: Uncaught Error: Call to a member function attributes() on array
Also tried:
$array->Customer['CustomerId'];
I get following error:
Notice: Trying to get property 'Customer' of non-object
Expecting to get 219196
I found the solution to the above problem. Not sure if it is the most elegant way to do it, but it returns result as expected. If there is a more efficient way to get the ContactId, I am open to suggestions.
print_r($array['GetCompanyCodeResponse']['GetCompanyCodeResult']
['Customers']['Customer']['attributes']['ContactId']);
You have followed some very bad advice on how to parse the XML, and completely thrown away the functionality of SimpleXML.
Specifically, the reason you can't run the attributes() method is that you've converted the SimpleXML object to a plain array using this ugly hack:
$array = json_decode( str_replace('#', '', json_encode((array)$body)), TRUE);
To use SimpleXML as its authors intended, I suggest you read:
The examples in the PHP manual
This reference answer on handling XML namespaces
Since you didn't paste the actual XML in the question, I'm going to take a guess that it looks like this:
<?xml version = "1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope">
<soap:Body xmlns="http://www.example.org/companyInfo">
<GetCompanyCodeResponse>
<GetCompanyCodeResult>
<Customers>
<Customer CustomerNo="103987" CustomerName="epds api testers Inc" ContactId="219196" />
</Customers>
</GetCompanyCodeResult>
</GetCompanyCodeResponse>
</soap:Body>
</soap:Envelope>
If that is in $response, we don't need to do any weirdness with str_replace or json_encode, we can use the methods built into SimpleXML to navigate around the XML:
$xml = new SimpleXMLElement($response);
// The Body is in the SOAP Envelope namespace
$body = $xml->children('http://www.w3.org/2001/12/soap-envelope')->Body;
// The element inside that is in some other namespace
$innerResponse = $body->children('http://www.example.org/companyInfo')->GetCompanyCodeResponse;
// We need to traverse the XML to get to the node we're interested in
$customer = $innerResponse->GetCompanyCodeResult->Customers->Customer;
// Unprefixed attributes aren't technically in any namespace (an oddity in the XML namespace spec!)
$attributes = $customer->attributes(null);
// Here's the value you were looking for
echo $attributes['ContactId'];
Unlike your previous code, this won't break if:
The server starts using a different local prefix instead of soap:, or adding a prefix on the GetCompanyCodeResponse element
The response comes back with more than one Customer (the ->Customer always means the same as ->Customer[0], the first child element with that name)
The Customer element has child elements or text content as well as attributes
It also allows you to use other features of SimpleXML, like using an xpath expression to search the document or even switching to the full DOM API for more complex operations.

XML node and values reversed using SimpleXMLElement and array_walk()

I am trying to build an XML element from an array in PHP using an example that was posted elsewhere on this site. The XML string is being created as expected however the nodes and their values are reversed. For Example:
$params = array(
"email" => 'me#gmail.com'
,"pass" => '123456'
,"pass-conf" => '123456'
);
$xml = new SimpleXMLElement('<root/>');
array_walk_recursive($params, array($xml, 'addChild'));
echo $xml->asXML();
Now what I am expecting to be returned is:
<?xml version="1.0"?>
<root>
<email>me#gmail.com</email>
<pass>123456</pass>
<pass-conf>123456</pass-conf>
</root>
However, what I keep getting is the node names as values and values as node names:
<?xml version="1.0"?>
<root>
<me#gmail.com>email</me#gmail.com>
<123456>pass</123456>
<123456>pass-conf</123456>
</root>
I have tested switching the key with the value in the $params array, but that seems like a lazy hack to me. I believe the issue lies within my callback in array_walk_recursive, but I'm not sure how exactly to make it work. I am open to recommendations on better ways to convert a PHP array to XML. I just tried this because it seemed simple and not convoluted. (haha..)
The problem with your code is that array_walk_recursive supplies the callback with the arguments value then key (in that order).
SimpleXMLElement::addChild accepts the arguments name then value (in that order).
Here's a less convoluted solution
foreach ($params as $key => $value) {
$xml->addChild($key, $value);
}
https://3v4l.org/oOHSb

How to get name of very first tag of XML with php's SimpleXML?

I am parsing XML strings using simplexml_load_string(), but I noticed that i don't get the name of the very first tag.
For example, I have these two xml strings:
$s = '<?xml version="1.0" encoding="UTF-8"?>
<ParentTypeABC>
<chidren1>
<children2>1000</children2>
</chidren1>
</ParentTypeABC>
';
$t = '<?xml version="1.0" encoding="UTF-8"?>
<ParentTypeDEF>
<chidren1>
<children2>1000</children2>
</chidren1>
</ParentTypeDEF>
';
NOTICE that they are nearly identical, the only difference being that one has the first node as <ParentTypeABC> and the other as <ParentTypeDEF>
then I just convert them to SimpleXML objects:
$o = simplexml_load_string($s);
$p = simplexml_load_string($t);
but then i have two equal objects, none of them having the "top" node's name appearing, either ParentTypeABC or ParentTypeDEF (I examine the objects using print_r()):
// with top node "ParentTypeABC"
SimpleXMLElement Object
(
[chidren1] => SimpleXMLElement Object
(
[children2] => 1000
)
)
// with top node "ParentTypeDEF"
SimpleXMLElement Object
(
[chidren1] => SimpleXMLElement Object
(
[children2] => 1000
)
)
So how I am supposed to know the top node's name? If I parse unknown XMLs and I need to know what's the top node name, what can I do?
Is there an option in simplexml_load_string() I could use?
I know there are MANY ways to parse XML's with PHP, but I'd like it to be as simple as posible, and to get a simple object or array I could navigate easily.
I made a simple example here to fiddle with.
SimpleXML has a getName() method.
echo $xml->getName();
This should return the name of the respective node, no matter if root or not.
http://php.net/manual/en/simplexmlelement.getname.php

Simplexml element will not store to PHP variable

I am writing a test script in php. I get back XML from the server in simplexml objects. Ive been parsing most fine, some using foreach loops and some directly from the elements. This one response just will not let me store the value to a PHP variable.
This is the specific response
<xml>
<status>1</status>
<count>1</count>
<device id="72220">
<udid>99000146864366</udid>
<devicename>Sprint Wwe</devicename>
<created>2014-07-01 13:22:27</created>
</device>
</xml>
Here is my parsing block
$cRes = $proxy->queryXML($section, 'retrieve', array("device_id" => "all"));
if($cRes->status == '1'){
$dvcID = $cRes->device[0]['id']->__toString();
$devicename = $cRes->device[0]->devicename->__toString();
if(empty($dvcID)) return $do;//
if(empty($devicename)) return $do2;//hacked break points
$res = array("deviceid" => $dvcID,
"devicename" => $devicename);
return $res;
}
The objective is to pull only id and devicename from the first device in an arbitrary amount of devices listed in the response. The php variables seem to not be empty as they dont return on my hacked break points(using notepad++). Ive tried casting them as (string) but they still show up with no data but do not fail the empty() test. Casting the id as an int turns it into a 0. What am I missing here?
The error response from the server is as follows
Last Query:Array
(
[device_id] =>
[devicename] =>
[return_type] => xml
[section] => devices
[action] => update
[api_key] => xxxxxxxxxxxxxxxxxx
)
Last Response<?xml version="1.0" encoding="utf-8"?>
<xml>
<status>0</status>
<error code="410">Required device POST variables not supplied</error>
</xml>

PHP SimpleXML Element parsing issue

I've come across a weird but apparently valid XML string that I'm being returned by an API. I've been parsing XML with SimpleXML because it's really easy to pass it to a function and convert it into a handy array.
The following is parsed incorrectly by SimpleXML:
<?xml version="1.0" standalone="yes"?>
<Response>
<CustomsID>010912-1
<IsApproved>NO</IsApproved>
<ErrorMsg>Electronic refunds...</ErrorMsg>
</CustomsID>
</Response>
Simple XML results in:
SimpleXMLElement Object ( [CustomsID] => 010912-1 )
Is there a way to parse this in XML? Or another XML library that returns an object that reflects the XML structure?
That is an odd response with the text along with other nodes. If you manually traverse it (not as an array, but as an object) you should be able to get inside:
<?php
$xml = '<?xml version="1.0" standalone="yes"?>
<Response>
<CustomsID>010912-1
<IsApproved>NO</IsApproved>
<ErrorMsg>Electronic refunds...</ErrorMsg>
</CustomsID>
</Response>';
$sObj = new SimpleXMLElement( $xml );
var_dump( $sObj->CustomsID );
exit;
?>
Results in second object:
object(SimpleXMLElement)#2 (2) {
["IsApproved"]=>
string(2) "NO"
["ErrorMsg"]=>
string(21) "Electronic refunds..."
}
You already parse the XML with SimpleXML. I guess you want to parse it into a handy array which you not further define.
The problem with the XML you have is that it's structure is not very distinct. In case it does not change much, you can convert it into an array using a SimpleXMLIterator instead of a SimpleXMLElement:
$it = new SimpleXMLIterator($xml);
$mode = RecursiveIteratorIterator::SELF_FIRST;
$rit = new RecursiveIteratorIterator($it, $mode);
$array = array_map('trim', iterator_to_array($rit));
print_r($array);
For the XML-string in question this gives:
Array
(
[CustomsID] => 010912-1
[IsApproved] => NO
[ErrorMsg] => Electronic refunds...
)
See as well the online demo and How to parse and process HTML/XML with PHP?.

Categories