读取xml元素

时间:2013-02-15 18:32:02

标签: php xml

我正在尝试读取结构如下的xml文件

<dictionary>
<head>

<DNUM />
<DEF value="definition1" />
<EXAMPLE value="example of 1" />
<EXAMPLE value="example of 1" />

<DNUM />
<DEF value="definition2" />
<EXAMPLE value="example of 2" />
<EXAMPLE value="example of 2" />
<EXAMPLE value="example of 2" />
<EXAMPLE value="example of 2" />

<DNUM />
<DEF value="definition3" />
<EXAMPLE value="example of 3" />


</head>
</ dictionary>

使用下面的代码,我可以阅读“head”标签内的所有定义或示例

 $result = $xml->xpath('//dictionary/head');
 while(list( , $node) = each($result)) {
   foreach($node->DEF as $def){
        echo  $def["value"]."<br>\n";
   }
 }

但我想得到该定义的每个定义和例子。我认为DNUM标签可以用于此,但由于它没有单独的打开和关闭,我无法找到如何得到我想要的结果。

4 个答案:

答案 0 :(得分:0)

我不确定我是否理解你的问题,但如果你需要找到DEF和DEF的例子,它可能就像

    $result = $xml->xpath('//dictionary/head/DEF');
 while(list( , $node) = each($result)) {
   foreach($node->EXAMPLE as $example){
        echo  $example["value"]."<br>\n";
   }
 }

答案 1 :(得分:0)

为什么不使用SimpleXMLElement?

$sxe = new SimpleXMLElement($xml);

$def = $sxe->head->dictionary->DEF->attributes(); //you can foreach this
//or
$def = $sxe['head']['dictionary']['DEF']->attributes(); //you can foreach this

您可以以类似的方式获取示例。 SXE可以像对象或数组一样使用,并通过foreach迭代。

我个人认为SimpleXMLElement是使用XML和PHP的最简单方法。

进一步阅读: http://www.php.net/manual/en/class.simplexmlelement.php

答案 2 :(得分:0)

我以这种方式解决了问题。

$result = $xml->xpath('//dictionary/headword/*[name()="DEF" or name()="EXAMPLE"]');
 foreach($result  as $res){
     echo $res["value"]."<br>";
 }

答案 3 :(得分:0)

由于您的XML结构不是分层结构,因此您只能计算。例如,以下DNUM元素的数量:

$name     = 'DNUM';
$elements = $xml->xpath("//$name");
$count    = count($elements);
foreach ($elements as $index => $element) {
    $count--;
    echo "Iteration $index\n";
    foreach ($element->xpath("following-sibling::*[count(./following-sibling::$name) = $count]") as $following) {
        echo $following->asXML(), "\n";
    }
    echo "\n";
}

示例性输出:

Iteration 0
<DEF value="definition1"/>
<EXAMPLE value="example of 1"/>
<EXAMPLE value="example of 1"/>

Iteration 1
<DEF value="definition2"/>
<EXAMPLE value="example of 2"/>
<EXAMPLE value="example of 2"/>
<EXAMPLE value="example of 2"/>
<EXAMPLE value="example of 2"/>

Iteration 2
<DEF value="definition3"/>
<EXAMPLE value="example of 3"/>