使用PHP

时间:2016-11-04 18:06:20

标签: php xml xml-parsing

我有一个类似于下面格式的XML文件,

<?xml version="1.0" encoding="UTF-8"?>
<section>
   <paragraph>val1</paragraph>
   <list>aa1</list>
   <list>aa2</list>
   <list>aa3</list>
   <paragraph>val2</paragraph>
   <list>bb1</list>
   <paragraph>val3</paragraph>
   <list>cc1</list>
   <list>cc2</list>
</section> 

我正在尝试编写一个PHP代码来打印结果,如下所示,

val1 - aa1
val1 - aa2
val1 - aa3
val2 - bb1
val3 - cc1
val3 - cc2

我在导出逻辑时遇到问题。有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

我认为最好的解决方案是更改xml结构并使用SimpleXml类。 但是这段代码可以满足您的需求:https://eval.in/672099

$string =<<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<section>
   <paragraph>val1</paragraph>
   <list>aa1</list>
   <list>aa2</list>
   <list>aa3</list>
   <paragraph>val2</paragraph>
   <list>bb1</list>
   <paragraph>val3</paragraph>
   <list>cc1</list>
   <list>cc2</list>
</section>
EOF;

 preg_match('#<section>(.*)<\/section>#s', $string, $section);
 preg_match_all('#<paragraph>(.*)<\/paragraph>#sU', $section[1], $paragraph);
 $lists = preg_split('#<paragraph>(.*)<\/paragraph>#sU', $section[1]);

 foreach($paragraph[1] as $key => $p){
    $list = null;
    preg_match_all('#<list>(.*)<\/list>#sU', $lists[$key+1], $list);
    foreach($list[1] as $l){
      echo $p . ' - ' . $l . PHP_EOL;
    }
 }

输出:

val1 - aa1
val1 - aa2
val1 - aa3
val2 - bb1
val3 - cc1
val3 - cc2

编辑

使用文件,您可以用

替换$ string assignation
$string = file_get_contents("path/to/file.xml");

答案 1 :(得分:-2)

爆炸后你可以使用正则表达式,比如$ x就是xml。

$y = explode('<paragraph>', $x);

unset($y[0]);
foreach($y as $z)
{
    preg_match_all('/(.*)<\/paragraph>?/', $z, $matches);
    preg_match_all('/<list>(.*)<\/list>/', $z, $matches2);
}

$ matches [1]和$ matches2 [1]是你想要的。