Reputation: 163
I have a XML and want to read values from only specific child nodes. Then I want to put those read values into an array and return this array at the end. So I want to get all values of name saved in an array and return this array. In the end, I want to display all values of this array beneath each other in an HTML file.
Here is my idea so far (which does not work obviously):
$items= simplexml_load_file('https://example.com/xml');
$itemList = array();
foreach ($items as $item->name) {
// Push the values of name of the item nodes into an array
}
return $itemList;
Here is the structure of the XML file:
<item>
<name>Name 1</name>
</item>
<item>
<name>Name 2</name>
</item>
<item>
<name>Name 3</name>
</item>
<item>
<name>Name 4</name>
</item>
Upvotes: 1
Views: 1108
Reputation: 47894
I don't do a lot of xml processing, so I tried the earlier posted answers (and the answer that came after I posted) with your sample xml and they didn't work for me.
I managed to process your data by writing your xml inside of a parent element before parsing, then looping and casting the name as a string.
Code: (Demo)
$xml = <<<XML
<item>
<name>Name 1</name>
</item>
<item>
<name>Name 2</name>
</item>
<item>
<name>Name 3</name>
</item>
<item>
<name>Name 4</name>
</item>
XML;
foreach (simplexml_load_string("<root>{$xml}</root>")->item as $item) {
$names[] = (string)$item->name;
}
var_export($names);
Output:
array (
0 => 'Name 1',
1 => 'Name 2',
2 => 'Name 3',
3 => 'Name 4',
)
Upvotes: 0
Reputation: 249
You can use json_encode()
and json_decode()
for converting xml data to string data type. After that, which tag you want to use, you can use this tag in foreach()
loop. And after that, you should to create an empty array and insert all string data to empty array.
$items = simplexml_load_file('https://example.com/xml');
$json = json_encode($items);
$array = json_decode($json,TRUE);
$names = array();
foreach ($array["item"] as $key => $value) {
$names[] = $value["name"];
}
print_r($names);
Result:
Array
(
[0] => Name 1
[1] => Name 2
[2] => Name 3
[3] => Name 4
)
Upvotes: 1
Reputation: 72299
You need to change foreach()
code as well as do assignment inside it:-
$itemList = array();
foreach ($items as $item) { //$item->name will not work here
$itemList[] = $item->name;
}
Upvotes: 2
Reputation: 54841
Iterate over each item and take it's name
property. Explicitly cast name
property to string
, cause by default $item->name
is not a string:
foreach ($items as $item) {
$itemList[] = (string)$item->name;
}
Upvotes: 3