我可以在SimpleXML上使用SQL语法吗?

时间:2014-01-14 14:38:36

标签: php simplexml where

我可以在SimpleXML上使用WHERE选择器(如SQL语法)吗?

示例XML

<?xml version="1.0" encoding="utf-8" ?> 
<documentElement>
        <row>
            <id>1</id>
            <name>David</name>
            <surname>Johnson</surname>
        </row>
        <row>
            <id>2</id>
            <name>Jack</name>
            <surname>Nixon</surname>
        </row>
</documentElement>

我的示例选择器

$where = "Jack";
$xml = "example.xml";
$sxml = simplexml_load_string($xml);
foreach ($sxml->row as $data=>$row)
{
if ($where == $data->name) // some code here
else // other some code here
}

请告诉我。

谢谢。

2 个答案:

答案 0 :(得分:4)

是的,有办法:XPath

$where = "Jack";
$xml = "example.xml";
$sxml = simplexml_load_string($xml);
var_dump($sxml->xpath('/documentElement/row/name[.="'.$where.'"]/..'));

答案 1 :(得分:0)

不,但你可以这样做:

$where = "Jack";
$xml = "example.xml";
$sxml = simplexml_load_string($xml);
foreach ($sxml->row as $row)
{
    if ($row->name == $where) {
        // ...
    } else {
        // other some code here
    }
}
相关问题