xpath选择并保存特定索引

时间:2012-08-02 08:17:01

标签: php xml xpath

我的php(simplexml)中有一个xml解析器,想在xpath下选择并保存一个索引元素

function startXML(&$resarrary, $path, $lang) {

if(file_exists($path)) {
    $xml = simplexml_load_file($path);
    if($xml) {      
        foreach($xml->xpath("//languageKey") as $cos) {
        utf8_encode($cos);

        // Select required languagekey 

        if ($cos[index] == $lang) {
        foreach($xml->xpath("//languageKey[@index='$lang']//label[@type='js']") as $cos) {
            ?>
                <table>
                    <tr>
                        <td><?php echo $cos ?></td>
                    </tr>
                </table>    
            <?php 
            array_push($resarrary,$cos);

            }

        } 

      }

    } 
    else {
        FALSE;
    }
}

}

表echo $ cos仅用于测试....它从我的xml文件中给出了我搜索的正确结果(在这种情况下,结果是“模式1”)

所以选择有效,但我怎样才能将结果(“模式1”)保存到数组?如果我尝试这个array_push(...)并使用print_r查看resarray我只获得simplexml xpath搜索的全部内容

数组([0] =&gt; SimpleXMLElement对象([@attributes] =&gt;数组([index] =&gt; list_mode_1 [type] =&gt; js)[0] =&gt;模式1))

如果我改变了行array_push($ resarrary,$ cos-&gt; attributes());我明白这个

数组([0] =&gt; SimpleXMLElement对象([@attributes] =&gt;数组([index] =&gt; list_mode_1 [type] =&gt; js)))

1 个答案:

答案 0 :(得分:0)

XML

<lKey index="default" type="array">
    <a index="list_mode_1" type="js">Mode 1</a>
    <b index="list_mode_2">Mode 2</b>
    <c index="list_mode_3">Mode 3</c>
</lKey>