在PHP中查询类似XPath的数组

时间:2016-10-31 03:42:31

标签: php xpath

我正在寻找一些能够在PHP中查询关联数组的方法/库:

$data = 
[
    'employees' => [
        [
            'name' => 'Alex',
            'age' => 32
        ],
        [
            'name' => 'Fill',
            'age' => 27
        ],
        [
            'name' => 'Alan',
            'age' => 25
        ]
    ]
];

array_xpath($data, "//employees[age=32]/name");// ['Alex']

1 个答案:

答案 0 :(得分:0)

<?php
function arrtoxml($arr,$dom=0,$item=0){
    if (!$dom){
        $dom = new DOMDocument("1.0");
    }
    if(!$item){
        $item = $dom->createElement("root");
        $dom->appendChild($item);
    }
    foreach ($arr as $key=>$val){
        $itemx = $dom->createElement(is_string($key)?$key:"item");
        $item->appendChild($itemx);
        if (!is_array($val)){
            $text = $dom->createTextNode($val);
            $itemx->appendChild($text);

        }else {
            arrtoxml($val,$dom,$itemx);
        }
    }
    return $dom->saveXML();
}


$data =
[
    'employees' => [
        [
            'name' => 'Alex',
            'age' => 32
        ],
        [
            'name' => 'Fill',
            'age' => 27
        ],
        [
            'name' => 'Alan',
            'age' => 25
        ]
    ]
];

$dom = new SimpleXMLElement( arrtoxml( $data ) );
$result = $dom -> xpath("//item[age=32]");
var_dump($result);