用php简单xml解析xml
我有以下xml文件:用php简单xml解析xml,php,xml,simplexml,Php,Xml,Simplexml,我有以下xml文件: <File> <Function name="for"> <Function name="if"> <Function name="if"> </Function> </Function> <Function name="else"> </
<File>
<Function name="for">
<Function name="if">
<Function name="if">
</Function>
</Function>
<Function name="else">
</Function>
</Function>
</File>
要做到这一点,仅仅获取包含函数的所有节点是不够的,我还需要获取顺序
我创建了一个名为Function的类,它有一个函数列表:
class Function{
/**
* @var int
*/
private $id;
/**
* @var string
*/
private $name;
/**
* @ORM\OneToMany(targetEntity="Function")
*/
private listFunctions;
现在每个函数都可以有嵌套函数。
我的分析如下:
$xml = simplexml_load_file('file.xml') or die("Error: Cannot create object");
$functions = array();
foreach ($xml->->File->children() as $f) {
// Iterate over <Function> tags under <File> tag (level-1 functions)
$function = new Function();
$function->setName($f['name']);
if(isset($f->Function)) {
foreach($f->children() as $cf){
//Iterate over level-2 functions
$cfunction = new Function();
$cfunction->setName($cf['name']);
$f->addListFunctions($cfunction);
}
}
$functions[] = $function;
}
但是我不知道我有多少级别,所以我需要用一种通用的方式来做。
我认为解决方法是使用递归函数,但我不习惯使用它,我不知道如何开始,甚至不知道它是否是正确的路径
有什么想法吗?逻辑是:-将代码放在函数中,其中第一个foreach检查中的值仍然是数组类型如果是,则再次调用此函数,如果否,则执行其他操作。逻辑是:-将代码放在函数中,其中第一个foreach检查中的值仍然是数组类型如果是,则再次调用此函数,如果没有,请做其他事情。
$xml = simplexml_load_file('file.xml') or die("Error: Cannot create object");
$functions = array();
foreach ($xml->->File->children() as $f) {
// Iterate over <Function> tags under <File> tag (level-1 functions)
$function = new Function();
$function->setName($f['name']);
if(isset($f->Function)) {
foreach($f->children() as $cf){
//Iterate over level-2 functions
$cfunction = new Function();
$cfunction->setName($cf['name']);
$f->addListFunctions($cfunction);
}
}
$functions[] = $function;
}
for{
if{
}
else{
}
}