Export Array of SimpleXMLElement objects to MySQL Database - php

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.

Related

PHP Get / check value from associative array in array of individual stdClass Objects

Having real issues with this. I want to be able to get a value from this data which is returned via an API.
ie get value by
$CM_user_customfields['Organisation'],
$CM_user_customfields->Organisation.
is that even possible? I have tried loops and rebuilding the array but i always end up with a similar results and perhaps overthinking it.
I can't use the [int] => as the number of custom fields will be changing a lot.
$CM_user_customfields = $CM_details->response->CustomFields ;
echo '<pre>' . print_r( $CM_user_customfields, true ) . '</pre>';
// returns
Array
(
[0] => stdClass Object
(
[Key] => Job Title
[Value] => Designer / developer
)
[1] => stdClass Object
(
[Key] => Organisation
[Value] => Jynk
)
[2] => stdClass Object
(
[Key] => liasoncontact
[Value] => Yes
)
[3] => stdClass Object
...
many thanks, D.
I recommend convert to associative array first:
foreach($CM_user_customfields as $e) {
$arr[$e->Key] = $e->Value;
}
Now you can access it as:
echo $arr['Organisation'];
You can also achieve it by: (PHP 7 can convert stdClass and will do the trick)
$arr = array_combine(array_column($CM_user_customfields, "Key"), array_column($CM_user_customfields, "Value")));

Get variable from JSON output with special character in object name

I cannot find how to get the results from this JSON post in PHP.
stdClass Object
(
[api_job_id] => 398438bf-c0a5-46fc-8774-70d2425e1ce7
[data] => Array
(
[0] => stdClass Object
(
[type] => MESSAGE
[message_id] => 15125005817130024103
[to] => xxx
[error_code] => 0
[#meta] => stdClass Object
(
[error] => stdClass Object
(
[error_desc] => NO_USER
[error_code] => 9
)
)
)
)
)
as you can see the meta has a # icon before it.
I can read all data to vars instead of the data in the #meta
I tried many ways like:
$result = $arrayResponse['#meta']['error']['error_desc'];
it's not working in PHP because of the # icon.
Any idea how I can get the values from these errors in #meta?
To refer to an object attribute with a name that doesn't make a valid variable, you can use braces:
$foo = json_decode($string);
var_dump($foo->{'#meta'});
Or pass a truthy value to json_decode() as the second argument, and you'll get back an array instead of an object:
$foo = json_decode($string, true);
var_dump($foo['#meta']);

get value from JSON string

I have a object as shown below and i want to extract data from
stdClass Object
(
[day1] => stdClass Object
(
[0] => 12.06.2015
[part1] => Array
(
[0] => 19.00
[1] => 22.00
)
[part2] => Array
(
[0] =>
[1] =>
)
)
)
How will i get date as shown above with key 0. I can get others as
$string->day1->part1[0]
How can i get date "12.06.2015" ? This seems to be complicated.
JSON string for reference
{"day1":{"0":"12.06.2015","part1":["19.00","22.00"],"part2":["",""]},"day2":{"0":"13.06.2015","part1":["09.00","12.00"],"part2":["13.00","17.00"]}}
used json_decode to decode it.
You can use this:
echo $string->day1->{0};
Or my preference, decode as an array with the second argument set to true in json_decode() to use this:
echo $string['day1'][0];

PHP for directory listing

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);

Comparing object values from DB with csv content

I have a function which gets me all students enrolled on a course on my local db. I need to cross check their usernames with usernames from a csv and output the ones who are NOT in the csv
Here's the output of the function:
Array (
[as.domingos] => stdClass Object ( [username] => as.domingos )
[m.menas] => stdClass Object ( [username] => m.menas )
[m.bexiga] => stdClass Object ( [username] => m.bexiga )
[spm] => stdClass Object ( [username] => spm ) )
And here's the csv format:
username;email;course1
userA;a#gmail.com;ABC
userB;b#gmail.com;ABC
m.menas;m.menas#gmail.com;ABC
m.bexiga;m.bexiga#gmail.com;ABC
spm;spm#gmail.com;ABC
My first thought was calling array_diff but it's not working. In this example above, the output would be as.domingos, because it's not in the csv.
$fp=fopen('sample.csv','r');
$numberofquitters=0;
$enrolinfo=' ';
fgetcsv($fp,1000,";");
while(($data=fgetcsv($fp,1000,";"))!==FALSE){
if(array_diff((array)$xpta->username,$data)){
//echo $xpto->username;
$enrolinfo=get_string('quitter','local_ecoclipaluno');
$numberofquitters++;
}
Any ideas?
Cheers.

Categories