XML routine elements using foreach ()

I have an XML file that needs PHP parsing. I upload a simplexml_load_file file to download the file as follows:

$xml = simplexml_load_file('Project.xml'); 

Inside this XML file is this structure:

 <?xml version="1.0" encoding="ISO-8859-1"?> <project> <name>Project 1</name> <features> <feature>Feature 1</feature> <feature>Feature 2</feature> <feature>Feature 3</feature> <feature>Feature 4</feature> </features> </project> 

What I'm trying to do is print the contents of the <name> along with the EACH <feature> element in the <features> . I am not sure how to do this because there is more than one element named <feature> . Any help is appreciated.

+4
source share
3 answers

to print the text, try the following:

 foreach($xml->features->feature as $key => $value) { echo $value; } 
+10
source

simplexml_load_file () returns an object.

Look at the structure with var_dump ($ xml):

 object(SimpleXMLElement)#1 (2) { ["name"]=> string(9) "Project 1" ["features"]=> object(SimpleXMLElement)#2 (1) { ["feature"]=> array(4) { [0]=> string(9) "Feature 1" [1]=> string(9) "Feature 2" [2]=> string(9) "Feature 3" [3]=> string(9) "Feature 4" } } } 

So, the code is as follows:

 <?PHP $xml = simplexml_load_file('test.xml'); echo $xml->name . "\n"; foreach($xml->features->feature as $f){ echo "\t$f\n"; } 

It will be displayed as:

 Project 1 Feature 1 Feature 2 Feature 3 Feature 4 

This is what I assume that you are after, more or less.

+1
source

You can do:

 foreach($xml->features->feature as $f) { echo $f."\n"; } 
0
source

Source: https://habr.com/ru/post/1307906/


All Articles