PHP Removing empty items from object - php

I have the following object, here printed as an array. This object is built from a SOAP request.
AdminInfo Object (
[Supplier] => Supplier Object (
[Party] => Party Object (
[OrgInfo] => OrgInfo Object (
[CompanyName] => Bobs
[IDInfo] => Array of IDInfo Objects (
[0] => IDInfo Object (
[IDQualifierCode] =>
[IDNum] =>
)
[1] => IDInfo Object (
[IDQualifierCode] => CompanyID
[IDNum] => 83e26599-d40g-4cba-9791-7d7c83de282c
)
[2] => IDInfo Object (
[IDQualifierCode] => TID
[IDNum] => BOBTID01020304
)
[3] => IDInfo Object (
[IDQualifierCode] => Token
[IDNum] => c784570e-044d-42c8-98fe-af9f7c1747f5
)
)
)
[ContactInfo] => ContactInfo Object (
[ContactJobTitle] =>
[Communications] => Comm Object (
[CommQualifier] =>
[CommPhone] =>
[CommEmail] =>
[Address] => Address Object (
[Address1] =>
[Address2] =>
[City] =>
[StateProvince] =>
[PostalCode] =>
[CountryCode] =>
)
)
[ContactName] => PersonName Object (
[FirstName] =>
[MiddleName] =>
[LastName] =>
)
)
)
)
[Company] => Company Object (
[Party] => Party Object (
[OrgInfo] => OrgInfo Object (
[CompanyName] => SF
[IDInfo] =>
)
[ContactInfo] =>
)
)
[Facility] => Facility Object (
[Party] => Party Object (
[OrgInfo] => Array of OrgInfo Objects (
)
[ContactInfo] => ContactInfo Object (
[ContactJobTitle] => Owner
[Communications] => Array of Comm Objects(
[0] => Comm Object (
[CommQualifier] => WP
[CommPhone] => 1234567890
)
[1] => Comm Object (
[CommQualifier] => SA
[Address] => Address Object (
[Address1] => 123 NE 14th St
[City] => Nowhere
[StateProvince] => ND
[PostalCode] => 12345
[CountryCode] => US
)
)
[2] =>
[3] =>
)
[ContactName] => PersonName Object (
[FirstName] => Bob
[MiddleName] =>
[LastName] => Tester
)
)
)
)
)
What I want to do is to remove all the empty elements and be returned with this object
AdminInfo Object (
[Supplier] => Supplier Object (
[Party] => Party Object (
[OrgInfo] => OrgInfo Object (
[CompanyName] => Bobs
[IDInfo] => Array of IDInfo Objects (
[0] => IDInfo Object (
[IDQualifierCode] =>
[IDNum] =>
)
[1] => IDInfo Object (
[IDQualifierCode] => CompanyID
[IDNum] => 83e26599-d40g-4cba-9791-7d7c83de282c
)
[2] => IDInfo Object (
[IDQualifierCode] => TID
[IDNum] => BOBTID01020304
)
[3] => IDInfo Object (
[IDQualifierCode] => Token
[IDNum] => c784570e-044d-42c8-98fe-af9f7c1747f5
)
)
)
)
)
[Company] => Company Object (
[Party] => Party Object (
[OrgInfo] => OrgInfo Object (
[CompanyName] => SF
)
)
)
[Facility] => Facility Object (
[Party] => Party Object (
[ContactInfo] => ContactInfo Object (
[ContactJobTitle] => Owner
[Communications] => Array of Comm Objects (
[0] => Comm Object (
[CommQualifier] => WP
[CommPhone] => 1234567890
)
[1] => Comm Object (
[CommQualifier] => SA
[Address] => Address Object (
[Address1] => 123 NE 14th St
[City] => Nowhere
[StateProvince] => ND
[PostalCode] => 12345
[CountryCode] => US
)
)
)
[ContactName] => PersonName Object (
[FirstName] => Bob
[LastName] => Tester
)
)
)
)
)
These attempts don't do it AT ALL; variable $AdminInfo is the Object above...
From solution here: strip null values of json object
$json = json_encode($AdminInfo);
$result = preg_replace('/,\s*"[^"]+":null|"[^"]+":null,?/', '', $json);
$echo $result;
From solution here: How to remove null values from an array?
$json = json_encode($AdminInfo); // convert to JSON
$arr = (array)json_decode($json); // convert to an array
$object = (object) array_filter((array) $arr); // filter the array
$result = json_encode($object); // convert it back to JSON
echo $result;
From here: PHP - How to remove empty entries of an array recursively?
function array_remove_empty($haystack)
{
foreach ($haystack as $key => $value) {
if (is_array($value)) {
$haystack[$key] = array_remove_empty($haystack[$key]);
}
if (empty($value)) {
unset($haystack[$key]);
}
}
return $haystack;
}
$json = json_encode($AdminInfo); // convert to JSON
$arr = (array)json_decode($json); // convert to an array
print_r(array_remove_empty($arr)); // run through array_remove_empty function and print
From solution here: Remove items from multidimensional array in PHP
function cleanArray($array) {
if (is_array($array)) {
foreach ($array as $key => $sub_array)
{
$result = cleanArray($sub_array);
if ($result === false) {
unset($array[$key]);
} else {
$array[$key] = $result;
}
}
}
if (empty($array)) {
return false;
}
return $array;
}
$json = json_encode($AdminInfo); // convert to JSON
$arr = (array)json_decode($json); // convert to an array
print_r(cleanArray($arr)); // run through cleanArray function and print
Edit
AdminInfo object as JSON:
{
"Supplier":{
"Party":{
"OrgInfo":{
"CompanyName":"Bobs",
"IDInfo":[
{
"IDQualifierCode":null,
"IDNum":""
},
{
"IDQualifierCode":"CompanyID",
"IDNum":"83e26599-d40g-4cba-9791-7d7c83de282c"
},
{
"IDQualifierCode":"TID",
"IDNum":"BOBTID01020304"
},
{
"IDQualifierCode":"Token",
"IDNum":"c784570e-044d-42c8-98fe-af9f7c1747f5"
}
]
},
"ContactInfo":{
"ContactJobTitle":"",
"Communications":{
"CommQualifier":null,
"CommPhone":"",
"CommEmail":"",
"Address":{
"Address1":"",
"Address2":"",
"City":"",
"StateProvince":null,
"PostalCode":"",
"CountryCode":null
}
},
"ContactName":{
"FirstName":"",
"MiddleName":"",
"LastName":""
}
}
}
},
"Company":{
"Party":{
"OrgInfo":{
"CompanyName":"SF",
"IDInfo":null
},
"ContactInfo":null
}
},
"Facility":{
"Party":{
"OrgInfo":[
],
"ContactInfo":{
"ContactJobTitle":"",
"Communications":[
{
"CommQualifier":null,
"CommPhone":"",
"CommEmail":"",
"Address":{
"Address1":"",
"Address2":"",
"City":"",
"StateProvince":null,
"PostalCode":"",
"CountryCode":null
}
},
null,
null,
null
],
"ContactName":{
"FirstName":"Bob",
"MiddleName":"",
"LastName":"Tester"
}
}
}
}
}

Requirements: Recursively scan nested arrays pruning out empty branches / items.
This is another 'tree walk'.
The only 'tricky' part is letting the processing higher up the tree know whether to add the current item into the output tree or not.
The function that processes a node will return an array that has a 'keep value' flag as well as the value to keep.
JSON Converted to array: Full Working code at eval.in
Output preserves original JSON Data Type: Full Working code at eval.in
Code:
function processList(array $list)
{
$listResult = ['keepValue' => false, // once set true will propagate upward
'value' => []];
foreach ($list as $name => $item ) {
if (is_null($item)) { // see is_scalar test
continue;
}
if (is_scalar($item)) { // keep the value?
if (!empty($item) || strlen(trim($item)) > 0) {
$listResult['keepValue'] = true;
$listResult['value'][$name] = $item;
}
} else { // new list... recurse
$itemResult = processList($item);
if ($itemResult['keepValue']) {
$listResult['keepValue'] = true;
$listResult['value'][$name] = $itemResult['value'];
}
}
}
return $listResult;
}
Run the function:
$source = json_decode($json, true);
$result = processList($source);
print_r($result['value']);
Output:
Array
(
[Supplier] => Array
(
[Party] => Array
(
[OrgInfo] => Array
(
[CompanyName] => Bobs
[IDInfo] => Array
(
[1] => Array
(
[IDQualifierCode] => CompanyID
[IDNum] => 83e26599-d40g-4cba-9791-7d7c83de282c
)
[2] => Array
(
[IDQualifierCode] => TID
[IDNum] => BOBTID01020304
)
[3] => Array
(
[IDQualifierCode] => Token
[IDNum] => c784570e-044d-42c8-98fe-af9f7c1747f5
)
)
)
)
)
[Company] => Array
(
[Party] => Array
(
[OrgInfo] => Array
(
[CompanyName] => SF
)
)
)
[Facility] => Array
(
[Party] => Array
(
[ContactInfo] => Array
(
[ContactName] => Array
(
[FirstName] => Bob
[LastName] => Tester
)
)
)
)
)

After a little bit of headscratching I came up with a recursive function that, like I suggested earlier, converts the object into an array to check if the variables are set to null.
If all variables inside that object are null, the parent is indexed to set the reference of the object to null.
I tried to explain and document the code as best as I can.
Please don't just copy the code and be done with it but read it trough and try to learn from the code I supplied.
/**
Unsets all empty variables in $object
*/
function loopTrough(&$object, &$parent = null, $key = null, $objectIsArray = false, $parentIsArray = false)
{
// Keep track of amount of vars and amount of null vars
$vars = 0;
$null = 0;
foreach($object as $index => $value)
{
$vars = $vars + 1;
// Also check if is array
$isArray = is_array($value);
// Check if is object
if (is_object($value) || $isArray) // using value here is save
{
// Loop trough the new object (or array) we found
if ($objectIsArray)
{
loopTrough($object[$index], $object, $index, $isArray, $objectIsArray);
}
else
{
loopTrough($object->{$index}, $object, $index, $isArray, $objectIsArray);
}
}
// Check if is null
if ($objectIsArray)
{
if (!isset($object[$index]) || $object[$index] == ""){
$null = $null + 1;
// We don't want to show null
unset($object[$index]);
}
}
else
{
if (!isset($object->{$index}) || $object->{$index} == "") // use $object->{index} here, and not $value because $value does not change when object reference is changed
{
$null = $null + 1;
// We don't want to show null
unset($object->{$index});
}
}
}
// If there are as much null variables as variables
if ($vars == $null && $parent !== null && $key !== null)
{
// Set the parent reference to null
if ($parentIsArray) // Example exludes arrays, uncomment this if you want values in arrays to be recurisvely set to null
{
// unset($parent[$key]);
}
else
{
unset($parent->{$key});
}
}
}
class Test
{
public $one;
public $two;
}
$test = new Test();
$test->one = new Test();
$test->one->two = "On";
$test->two = new Test();
$test->two->one = new Test();
var_dump($test);
loopTrough($test);
var_dump($test);

Like I suggested earlier you COULD convert the object into an array and recursively loop trough the elements to check if they are null.
The recursive function is going to be quite complicated since you don't just want to remove null variables, but remove everything that contains null only variables.
Heres an example without the recursion which just removes null variables from an object:
class A
{
public $var = "aVar";
public $var1 = null;
}
$a = new A();
var_dump($a);
$array = (array)$a;
foreach($array as $key => $value)
{
if (is_null($value)){
unset($array[$key]);
}
}
var_dump($array);

seriously don't got time to test it, but edit: tested it, had a bug in the original code (had clean_iterable(NULL,$v); instead of clean_iterable(NULL,$v[$key]);, fixed it, this seem to work:
function clean_iterable(Iterable $v=NULL,Iterable &$vv=NULL):Iterable{
if(isset($vv)){
$v=&$vv;
}
if(empty($v)){
return $v;
}
foreach($v as $key=>$val){
if(empty($val)){
unset($v[$key]);
}elseif(is_iterable($val)){
clean_iterable(NULL,$v[$key]);
}
}
return $v;
}

Related

Updating the value in existing JSON data by key in PHP

I have JSON data and want to update the value by key.
JSON:
{
"language":"en",
"education":[
{
"unit":"e1",
"language":"en"
}
],
"membership":[
{
"uei":"21",
"Uifed":"failed"
}
]
}
I want to change the value of uifed from "failed" to "success".
What have I done?
$json = '{"language":"en","education":[{"unit":"e1","language":"en"}],"membership":[{"uei":"21","Uifed":"failed"}]}';
$arrayData = json_decode($json, true);
$replacementData = array('Uifed' => 'success');
$newArrayData = array_replace_recursive($arrayData, $replacementData);
echo var_dump($newArrayData);
Result:
NULL
How can I do that?
That's not how array_replace_recursive works; the replacement arrays need to have the same structure as the one you are replacing into. For your sample data, this will work:
$json = '{"language":"en","education":[{"unit":"e1","language":"en"}],"membership":[{"uei":"21","Uifed":"failed"}]}';
$arrayData = json_decode($json, true);
$replacementData = array('membership' => array(array('Uifed' => 'success')));
$newArrayData = array_replace_recursive($arrayData, $replacementData);
print_r($newArrayData);
Output:
Array
(
[language] => en
[education] => Array
(
[0] => Array
(
[unit] => e1
[language] => en
)
)
[membership] => Array
(
[0] => Array
(
[uei] => 21
[Uifed] => success
)
)
)
array_walk_recursive can be used to do what you want:
$replacementData = array('Uifed' => 'success');
array_walk_recursive($arrayData, function (&$value, $key) use ($replacementData) {
$value = $replacementData[$key] ?? $value;
});
print_r($arrayData);
Output:
Array
(
[language] => en
[education] => Array
(
[0] => Array
(
[unit] => e1
[language] => en
)
)
[membership] => Array
(
[0] => Array
(
[uei] => 21
[Uifed] => success
)
)
)
Demo on 3v4l.org
Simple example with foreach and passing values by reference:
$json = '{"language":"en","education":[{"unit":"e1","language":"en"}],"membership":[{"uei":"21","Uifed":"failed"}]}';
$arrayData = json_decode($json, true);
foreach ($arrayData['membership'] as &$membership) {
if ('failed' === $membership['Uifed']) {
$membership['Uifed'] = 'success';
}
}
print_r($arrayData);
Fiddle.

PHP - How do I unset an array index by value inside that index

I have an array of objects ($response) that looks like this:
Array
(
[0] => stdClass Object
(
[CardNumber] => 5897853070424xxx
[CardHolderName] => P Stoltz
[CardHolderContactNumber] =>
[CardHolderEmailAddress] =>
[CardExpiryDate] => 2017-09-01T00:00:00
[CardHolderTypeID] => 2
[LastUsedDate] => 2017-05-25T00:00:00
)
[1] => stdClass Object
(
[CardNumber] => 589785304326xxx
[CardHolderName] => J Stoltz
[CardHolderContactNumber] =>
[CardHolderEmailAddress] =>
[CardExpiryDate] => 2017-09-01T00:00:00
[CardHolderTypeID] => 2
[LastUsedDate] => 2017-05-25T00:00:00
)
)
Now, I need to unset the entire object where CardNumber != '589785304326xxx'
I have tried this:
$cardnumber = '5897853070424xxx';
foreach( $response as $res )
{
if($res->CardNumber != $cardnumber)
{
unset($res);
}
}
This does nothing. Any suggestions?
What you have tried will only unset the current object in the loop. You need to do the following:
foreach($response as $key => $res) {
if($res->CardNumber != $cardnumber) {
unset($response[$key], $res);
continue;
}
}
Use unset() inside the loop.
eg:
unset('key value', 'your array name');

grabbing only certain array inside array

Basically, I'm receiving an array() from the Yahoo Messenger API in PHP and am in the process of developing an notification system, It returns an array with both the IM received from an chat and my contacts.
Array (
[0] => Array
(
[message] => Array
(
[status] => 1
[sequence] => 0
[sender] => SenderCurtis
[receiver] => receiverCurtis
[msg] => #1
[timeStamp] => 1374187598
[hash] => y2qlDf8uTq8tXzgzrsSMyjQB+W2uDg==
[msgContext] => y2qlDf8uTq8tXzgzrsSMyjQB+W2uDg==
)
)
[1] => Array
(
[buddyInfo] => Array
(
[sequence] => 1
[contact] => Array
(
[0] => Array
(
[sender] => SenderCurtis
[presenceState] => 0
[avatarUser] => 0
[avatarPreference] => 0
[clientCapabilities] => 8915971
[clientUserGUID] => MI7STHUYOAMCGE5TNTY7CJPFWM
)
)
)
)
[2] => Array
(
[message] => Array
(
[status] => 1
[sequence] => 2
[sender] => SenderCurtis
[receiver] => receiverCurtis
[msg] => #2
[timeStamp] => 1374187601
[hash] => 3+2s9sIvjPRdvneQsMgVNCKBTFgKwQ==
[msgContext] => 3+2s9sIvjPRdvneQsMgVNCKBTFgKwQ==
)
)
[3] => Array
(
[buddyInfo] => Array
(
[sequence] => 3
[contact] => Array
(
[0] => Array
(
[sender] => myContactUser1#yahoo.com
[presenceState] => 0
[avatarUser] => 0
[avatarPreference] => 0
[clientCapabilities] => 8915971
[clientUserGUID] => UQU3WV7ZOZ2OTGLJQUE2QJU4ZU
)
)
)
)
)
How can I grab just the message array() and iterate through it? such as "Message 1", "Message2" etc...
If you're trying to filter the array values for the key 'message', you could do something like this in PHP:
$messages = array();
foreach ($response as $key => $data) {
if (array_key_exists('message', $data)) {
$msgArray = $data['message'];
$messages[] = $msgArray;
}
}
In the above sample, I'm storing the messages in their own array. But you could process the data right inside the for-loop too, if you want that.
I think that array_map() is the function you are looking for here. The array_map function allows you to execute a callback on each element of an existing array and assemble a new array consisting only of the values returned by the callback.
What you would want to do is something like this :
$data = // lets assume this is the data you received
$messages_data = array_map( "extract_message", $data );
function extract_message( $data_item ){
if ( array_key_exists( 'message', $data_item ) ){
return $data_item[ 'message' ];
}
}
Now your $message_data array will contain only the message arrays from the original array.
foreach ($var[0] as $key => $value)
{
do things with each message
}
where $var is substituted for your actual variable name
Just filter your array using array_filter.
$messages = array_filter($data, function($a){ return isset($a["message"]); });
Then use array_map to get rid of the unwanted intermediate array.
$messages = array_map(function($a){ return $a["message"]; }, $message);
then you can iterate over it with a foreach or whatever.
Because I like SPL iterators here another solution. Works with PHP >= 5.1.0.
class MessageIterator extends FilterIterator
{
public function accept()
{
return array_key_exists('message', $this->getInnerIterator()->current());
}
public function current()
{
$current = parent::current();
return $current['message'];
}
}
$iterator = new MessageIterator(new ArrayIterator($array));
foreach ($iterator as $message) {
print_r($message);
}

Grouping multidimensional array by two values

I have arrays like this.
[11] => Array
(
[transactioncurrencyid] => Array
(
[!name] => US Dollar
[!] => {041E3DC9-D938-DD11-982C-0013724C58B7}
)
[smi_processingmonth] => Array
(
[!date] => 6/1/2011
[!time] => 2:27 PM
[!] => 2011-06-01T14:27:00-07:00
)
[smi_cchistoryid] => {678C5036-9EAA-E111-88E0-00155D010302}
[smi_includeindeal] => Array
(
[!name] => No
[!] => 0
)
[smi_locationid] => Array
(
[!name] => 1134 Hooksett Rd
[!] => {5CC1585B-91AA-E111-88E0-00155D010302}
)
)
[12] => Array
(
[transactioncurrencyid] => Array
(
[!name] => US Dollar
[!] => {041E3DC9-D938-DD11-982C-0013724C58B7}
)
[smi_processingmonth] => Array
(
[!date] => 5/1/2011
[!time] => 2:27 PM
[!] => 2011-05-01T14:27:00-07:00
)
[smi_cchistoryid] => {688C5036-9EAA-E111-88E0-00155D010302}
[smi_includeindeal] => Array
(
[!name] => No
[!] => 0
)
[smi_locationid] => Array
(
[!name] => 1134 Hooksett Rd
[!] => {5CC1585B-91AA-E111-88E0-00155D010302}
)
)
How can i group them by location id then by smi_processingmonth
So I get something like this
[1134 Hooksett Rd] => Array
(
[ 5/1/2011] = array(
[transactioncurrencyid] => Array
(
[!name] => US Dollar
[!] => {041E3DC9-D938-DD11-982C-0013724C58B7}
)
[smi_processingmonth] => Array
(
[!date] => 5/1/2011
[!time] => 2:27 PM
[!] => 2011-05-01T14:27:00-07:00
)
[smi_cchistoryid] => {688C5036-9EAA-E111-88E0-00155D010302}
[smi_includeindeal] => Array
(
[!name] => No
[!] => 0
)
[smi_locationid] => Array
(
[!name] => 1134 Hooksett Rd
[!] => {5CC1585B-91AA-E111-88E0-00155D010302}
)
)
[1/1/2011] = array(
[transactioncurrencyid] => Array
(
[!name] => US Dollar
[!] => {041E3DC9-D938-DD11-982C-0013724C58B7}
)
[smi_processingmonth] => Array
(
[!date] => 6/1/2011
[!time] => 2:27 PM
[!] => 2011-06-01T14:27:00-07:00
)
[smi_cchistoryid] => {678C5036-9EAA-E111-88E0-00155D010302}
[smi_includeindeal] => Array
(
[!name] => No
[!] => 0
)
[smi_locationid] => Array
(
[!name] => 1134 Hooksett Rd
[!] => {5CC1585B-91AA-E111-88E0-00155D010302}
)
)
)
I have tried
foreach($array as $keys)
{
$key = $keys['smi_processingmonth']['!date'];;
if (!isset($groups[$key]))
{
$groups[$key] = array($keys);
} else {
$groups[$key][] = $keys;
}
}
$newGroups = array();
if(is_array($groups))
{
foreach($groups as $cats => $values)
{
foreach($values as $itemValues){
$st = rtrim(trim($itemValues['smi_locationid']['!']));
$key = $st;
if (!isset($newGroups[$key]))
{
$newGroups[$key] = array($groups);
} else {
$newGroups[$key][] = $itemValues;
}
}
}
}
Thanks!
Taking from Johan with a few modifications:
avoid ltrim if already using trim
put in a function, I can use temporary variables to maintain readability
add a final [], to avoid nasty $name/$date collision, out of original request, but safer
function compactArray($data)
{
$new_structure = array();
foreach ( $data as $row )
{
$name = trim($row['smi_locationid']['!name']);
$date = trim($row['smi_processingmonth']['!date']);
$new_structure[ $name ][ $date ][] = $row;
}
return $new_structure;
}
Ehm, i have not tested it. But isn't it just:
$new_structure = array();
foreach ( $data as $row ) {
$key1 = rtrim(trim($row['smi_locationid']['!name']));
$key2 = rtrim(trim($row['smi_processingmonth']['!date']));
$new_structure[$key1][$key2] = $row;
}
This code could use some isset()s, but i decided to keep them out for clarity.
The following produces your desired output array, correctly sorted:
function transaction_datecmp($tran1, $tran2)
{
return strtotime($tran1['smi_processingmonth']['!']) -
strtotime($tran2['smi_processingmonth']['!']);
}
$output_arr = array();
foreach ($input_arr as $transaction) {
$location = $transaction['smi_locationid'] ['!name'];
$date = $transaction['smi_processingmonth']['!date'];
$output_arr[$location][$date] = $transaction;
}
ksort($output_arr); // sorts by location
foreach ($output_arr as &$transaction_arr) {
uasort($transaction_arr, 'transaction_datecmp');
}
Your data structure relies on the assumption that there cannot be two transactions on the same day, which is a somewhat dangerous assumption. Also using a location as a key is far from ideal (because of spelling, location changes, etc.) - unless it really should group things, like for paper mailing.
Data cleanup, like trimming strings, should be done beforehand, ideally at data input time.

how to access array objects differently and dynamically

there is a xml document that i'm parsing to array..
how can i access those array objects and save them in new variables..?
this is piece of php code that is parsing
$contents = file_get_contents('test.xml');
$xml = simplexml_load_string($contents);
print_r($xml);
here is the xml that is being parsed
<?xml version='1.0'?>
<document>
<txtmsg>
<smstel>1234567</smstel>
<smstxt></smstxt>
<smsdir>Send</smsdir>
<smstime>06/01/2010 7:54:48 am</smstime>
</txtmsg>
<txtmsg>
<smstel>33333333</smstel>
<smstxt>Test sms hhTes12222222</smstxt>
<smsdir>Send</smsdir>
<smstime>06/01/2010 7:54:48 am</smstime>
</txtmsg>
<Contacts>
<conttime>06/01/2010 8:19:05 am</conttime>
<cnt>
<fn>Abc</fn>
<ln>Def</ln>
<cnttel>123456</cnttel>
<cntmtel>3333333</cntmtel>
<cntemail>abc#hotmail.com</cntemail>
</cnt>
<cnt>
<fn>def</fn>
<ln>ghi</ln>
<cnttel>234234</cnttel>
<cntmtel>2424</cntmtel>
<cntemail>df#hotmail.com</cntemail>
</cnt>
</Contacts>
</document>
and this is output.
SimpleXMLElement Object ( [txtmsg] => Array ( [0] => SimpleXMLElement Object ( [smstel] => 1234567 [smstxt] => SimpleXMLElement Object ( ) [smsdir] => Send [smstime] => 06/01/2010 7:54:48 am ) [1] => SimpleXMLElement Object ( [smstel] => 33333333 [smstxt] => Test sms hhTes12222222 [smsdir] => Send [smstime] => 06/01/2010 7:54:48 am ) ) [Contacts] => SimpleXMLElement Object ( [conttime] => 06/01/2010 8:19:05 am [cnt] => Array ( [0] => SimpleXMLElement Object ( [fn] => Abc [ln] => Def [cnttel] => 123456 [cntmtel] => 3333333 [cntemail] => abc#hotmail.com ) [1] => SimpleXMLElement Object ( [fn] => def [ln] => ghi [cnttel] => 234234 [cntmtel] => 2424 [cntemail] => df#hotmail.com ) ) ) )
how can i access each element of xml individually.. like smstel,smstxt,smsdir etc
Maybe I'm over simplifying it, but a loop.
foreach($xml->txtmsg as $txtmsg) {
echo $txtmsg->smstel;
echo $txtmsg->smstxt;
// more elements...
}
Note: When using XML it helps to be aware of the schema. Meaning the above example is specific to those elements you mentioned. Nonetheless, it should help you get started.
this is the best way you can do that..
foreach($xml->txtmsg as $txtmsg) {
echo $txtmsg->smstel;
// more elements...
}
Easy
(string)$xml->txtmsg->smstel
Same goes for params and lists.. its either an object property, or an array
echo $xml->txtmsg[0]->smstel; // 1234567
echo $xml->txtmsg[1]->smstel; // 3333333
$smsTel = (string) $xml->txtmsg[0]->smstel; // 1234567
To literally convert the <txtmsg> sections to a multidimensional array, you could do:
$array = array();
foreach ($xml->txtmsg as $msg) {
$array[] = array (
'smstel' => (string) $msg->smstel,
'smstxt' => (string) $msg->smstxt,
'smsdir' => (string) $msg->smsdir,
'smstime' => (string) $msg->smstime
);
}
print_r($array);
/*
Array
(
[0] => Array
(
[smstel] => 1234567
[smstxt] =>
[smstel] => Send
[smstime] => 06/01/2010 7:54:48 am
)
[1] => Array
(
[smstel] => 33333333
[smstxt] => Test sms hhTes12222222
[smstel] => Send
[smstime] => 06/01/2010 7:54:48 am
)
)
*/
here is the code.
it will be convert you SimpleXML Object to Array
function convertXmlObjToArr($obj, &$arr)
{
$children = $obj->children();
foreach ($children as $elementName => $node)
{
$nextIdx = count($arr);
$arr[$nextIdx] = array();
$arr[$nextIdx]['#name'] = strtolower((string)$elementName);
$arr[$nextIdx]['#attributes'] = array();
$attributes = $node->attributes();
foreach ($attributes as $attributeName => $attributeValue)
{
$attribName = strtolower(trim((string)$attributeName));
$attribVal = trim((string)$attributeValue);
$arr[$nextIdx]['#attributes'][$attribName] = $attribVal;
}
$text = (string)$node;
$text = trim($text);
if (strlen($text) > 0)
{
$arr[$nextIdx]['#text'] = $text;
}
$arr[$nextIdx]['#children'] = array();
convertXmlObjToArr($node, $arr[$nextIdx]['#children']);
}
return;
}
you will get output in this format
Array
(
#name => books
#attributes => array ( )
#children => array
(
array
(
#name => novel
#attributes => array ( author => John Doe )
#children => array
(
array ( #name => title, #attributes => array ( ), #text => John's Novel )
)
)
)
)

Categories