I start from xml file with following input:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<severa>
<mesaj id="6caca93f" tip="ATENTIONARE"cod="GALBEN"" />
<mesaj id="6caca93g" tip="ATENTIONARE" cod="GALBEN" />
</severa>
Using PHP with xml2Array function I obtain below array:
Array
(
[0] => Array
(
[#attributes] => Array
(
[id] => 6caca93f
[tip] => ATENTIONARE
[cod] => GALBEN
)
)
[1] => Array
(
[#attributes] => Array
(
[id] => 6caca93g
[tip] => ATENTIONARE
[cod] => GALBEN
)
)
)
I read this result with foreach and insert this 2 records into MySql.
Now the problem: this works only for multiple records in xml (>2). If I have only one record in xml the array look like below and no row is inserted. Could you please advice what I should do?
Seems that this array with a single entry have a different form. I hope this is not the reason
Thank you so much!
Array
(
[#attributes] => Array
(
[id] => 6caca93f
[tip] => ATENTIONARE
[cod] => GALBEN
)
)
Foreach is like this:
foreach ($a as $row) {
$atributes = $row['#attributes'];
$id = $atributes['id'];
$tip = $atributes['tip'];
$cod = $atributes['cod'];
mysqli_stmt_execute($st);
}
Your xml2Array function is treating a single record differently from a list of records, adding an extra dimension in the second case. You need to treat the first case specially.
if (isset($a['#attributes'])) { // Single record, turn it into an array
$a = array($a);
}
Then your loop will work for both cases.
Related
I am working with php and arrays, I have multiple arrays like following
Array
(
[0] => Array
(
[wallet_address] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
)
[1] => Array
(
[wallet_address] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
[2] => Array
(
[wallet_address] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
and so on....
And i want to make them in single array with comma like following way
$set = array("0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx","0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx","0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
How can i do this ?Here is my current code but not working,showing me same result(0,1,2 keys),Where i am wrong ?
$GetUserFollower; //contaning multiple array value
$set=array();
foreach($GetUserFollower as $arr)
{
$set[]=$arr;
}
echo "<pre>";print_R($set);
The original array is an Assoc array and therefore the wallet_address needs to be addressed specifically in a loop. Or you could use the array_column() builtin function to achieve the same thing.
$GetUserFollower; //contaning multiple array value
$set=array();
foreach($GetUserFollower as $arr)
{
$set[] = $arr['wallet_address'];
}
echo "<pre>";print_r($set);
Or
$new = array_column($GetUserFollower, 'wallet_address');
print_r($new);
RESULT
Array
(
[0] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
[1] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
[2] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
Your comments are making me think you want an array without a key, which is impossible. If you do this with the example you show in your comments
$set = array("0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx","0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx","0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
print_r($set);
You will see
Array
(
[0] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
[1] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
[2] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)
I have to access to all values stored in a big multidimensional array, here's an example of print_r the array:
Array
(
[Novedad] => Array
(
[#attributes] => Array
(
[CUNENov] => 4545454545
)
)
[Periodo] => Array
(
[#attributes] => Array
(
[FechaIngreso] => 1998-12-12
[FechaRetiro] => 2021-11-12
[FechaLiquidacionInicio] => 2021-05-01
[FechaLiquidacionFin] => 2021-05-30
[TiempoLaborado] => 10829
[FechaGen] => 2021-05-05
)
)
[Devengados] => Array
(
[Basico] => Array
(
[#attributes] => Array
(
[DiasTrabajados] => 30
[SueldoTrabajado] => 1258955.00
)
)
)
)
The thing I want to do is extract the values from that array, I have tried this way:
<?php
$cunenov = $array['Novedad']['#attributes']['CUNENov'];
but doesn't work..
Any suggests?. Thanks in advance.
I wanted you to see the "constructed" array and the outputs .. Stand alone, this php works .. Paste it into a stand alone php file and determine what you're doing differently to not achieve the same result.
Building out the array, and then print_r so you can validate it's the same structure as your array.
<?php
$test = Array();
$test['Novedad'] = array();
$test['Novedad']['#attributes'] = array();
$test['Novedad']['#attributes']['CUNENov'] = 4545454545;
print_r( $test );
Yields:
Array
(
[Novedad] => Array
(
[#attributes] => Array
(
[CUNENov] => 4545454545
)
)
)
Then we echo:
$cunenov = $test['Novedad']['#attributes']['CUNENov'];
echo "Value is $cunenov";
Yields
Value is 4545454545
So I want to delete an array element from a JSON array based on an id in a sub-array. I know it sounds weird. Here's an example of the array. I want to delete the entire array [0] based on the [dealer][id] array where the [id] = 20220 in this example.
Array
(
[results] => Array
(
[offset] => 1
[length] => 15
[data] => Array
(
[0] => Array
(
[dealer] => Array
(
[id] => 20220
[name] => apple
)
)
)
)
}
In reality there are a lot more elements in the [results] array. I'm not sure how to go about it.
Any help is greatly appreciated!
Loop thru data key first then check if dealer id matches the searched id
$id = 20220;
foreach ($array['results']['data'] as $key => $value) {
if ($value['dealer']['id'] == $id) {
unset($array['results']['data'][$key]);
}
}
use array_filter,
$array['results']['data'] = array_filter($array['results']['data'], function($v){return $v['dealer']['id'] != 20220;});
I have an xml file with the following structure:
<categories>
<category>
<id>3</id>
<title><![CDATA[Testname]]></title>
<text><![CDATA[]]></text>
<keywords><![CDATA[]]></keywords>
<description><![CDATA[]]></description>
</category>
</categories>
Now I'm loading this file and creating an array of it:
$xmlData = simplexml_load_file( 'categories.xml', null, LIBXML_NOCDATA);
$array = json_decode(json_encode($xmlData), true);
That generates me the following Result (print_r Output):
Array
(
[#attributes] => Array
(
[version] => 1.0
)
[categories] => Array
(
[category] => Array
(
[0] => Array
(
[id] => 3
[title] => Testname
[text] => Array
(
)
[keywords] => Array
(
)
[description] => Array
(
)
)
)
)
)
Here is my question, how could I remove those empty arrays? I tried it with array Filter, but this didn't work. (I need the keys, but they should be empty)
I know there would be a way, in my next step where I'm renaming the array keys as needed, i could check for empty arrays in the foreach loop, but I think there is an easier way, because every field (except id) could be empty in the xml file.
foreach($array['categories']['category'] as $key => $category){
$results[$key]['id'] = $category['id'];
$results[$key]['headline'] = $category['title'];
$results[$key]['content'] = $category['text'];
$results[$key]['metaKeywords'] = $category['keywords'];
$results[$key]['metaDescription'] = $category['description'];
}
Does someone has an idea, what i could do after the json_decode? Or is there an easier way for all I'm trying to accomplish here?
Thanks!
Every time I see someone use that json_decode(json_encode()) hack, it makes me sad. You don't need to turn the SimpleXML object into an array to loop over it, just read the usage examples in the manual.
If you loop over the SimpleXML object directly, you will never get those arrays, so will never need to remove them:
$xmlData = simplexml_load_file('categories.xml'); // LIBXML_NOCDATA is NOT needed
foreach($xmlData->categories->category as $key => $category){
$results[$key]['id'] = (string)$category->id;
$results[$key]['headline'] = (string)$category->title;
$results[$key]['content'] = (string)$category->text;
$results[$key]['metaKeywords'] = (string)$category->keywords;
$results[$key]['metaDescription'] = (string)$category->description;
}
The (string) tells SimpleXML you want the text content of a particular element (including CDATA), and will give you an empty string for the empty elements.
Hope this will work. PHP code demo
<?php
$result=Array
(
"categories" => Array
(
"category" => Array
(
0 => Array
(
"id" => 3,
"title" => "Testname",
"text" => Array
(
),
"keywords" => Array
(
),
"description" => Array
(
)
)
)
)
);
$results=array();
foreach($result['categories']['category'] as $key => $category){
$results[$key]['id'] = $category['id'];
$results[$key]['headline'] = $category['title'];
$results[$key]['content'] = is_array($category['text']) && count($category['text'])>0 ? $category['text'] : false;
$results[$key]['metaKeywords'] = is_array($category['keywords']) && count($category['keywords'])>0 ? $category['keywords'] : false;
$results[$key]['metaDescription'] = is_array($category['description']) && count($category['description'])>0 ? $category['description'] : false;
$results[$key]=array_filter($results[$key]);
}
print_r($results);
I'm close to finishing a script which uses simplexml to process some data but I am stuck at the last.
Well, not stuck, but curious and stuck.
$tmp contains my XML (approx 750k) and the goal is to get it into a format for fputcsv (a parent array containing an array for each row).
The below works, but instead of a nice clean array that I can use fputcsv and send back to user there is a lot of overhead which I do not need for writing to a CSV file and which will create me problems no doubt with fputcsv. I have cleaned the output up into just a couple of header columns and just a couple of rows, but in reality there are 20 columns and hundreds of rows. Anyway to clean before fputcsv?
// Process XML response into arrays for fputcsv
$csv = array();
$xml = simplexml_load_string($tmp);
// Create array and loop each column for header row
$header_row = array();
foreach ($xml->RESPONSE->DATA->HEADER->COLUMN as $column) {
$header_row[] = $column;
}
$csv[] = $header_row;
// Create array and loop each column for header row
foreach ($xml->RESPONSE->DATA->ROW as $row) {
$data_row = array();
foreach ($row->COLUMN as $datacolvalue){
$data_row[] = $datacolvalue;
}
$csv[] = $data_row;
unset($data_row);
}
// Output var to check for accuracy (later add fputcsv)
var_dump($csv);
Output (print_r - can var_dump if required):
Array
(
[0] => Array
(
[0] => SimpleXMLElement Object
(
[0] => date
)
[1] => SimpleXMLElement Object
(
[0] => name
)
)
[1] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[data_type] => text
)
[0] => Aug 01, 2011
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[data_type] => text
[id] => 8699636
)
[0] => bfxgbfgxbfbgxfsfsdf
)
)
[2] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[data_type] => text
)
[0] => Aug 01, 2011
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[data_type] => text
[id] => 8699694
)
[0] => bfxgbfgxbfbgxf
)
)
)
Desired output (extrapolated for each additional column and removing #attributes):
array(
array("date","name"),
array("Aug 01, 2011","bfxgbfgxbfbgxfsfsdf"),
array("Aug 01, 2011","bfxgbfgxbfbgxf")
)
Try changing
foreach ($xml->RESPONSE->DATA->HEADER->COLUMN as $column) {
to
$columns = (array)$xml->RESPONSE->DATA->HEADER->COLUMN;
foreach ($columns as $column) {
That should convert the SimpleXML objects to simple arrays. Which should remove the "overhead". Do the same for foreach ($row->COLUMN as $datacolvalue){.
Answering my own question, because I probably didn't explain it well enough, but specifying a (string) got me to where I needed to be.