php - xml。是否可以在不循环遍历 xml 文件的所有数据的情况下访问特定的 xml 节点

php - xml. Is it possible to access particular xml node without looping through all data of xml file

Xml 这样的文件

<xml>

<Categories>
<OneSubcategory>

<Id>4</Id>
<CategoriesUrl>cars</CategoriesUrl>

<Id>5</Id>
<CategoriesUrl>staff-required</CategoriesUrl>

</OneSubcategory>
</Categories>

</xml>

想要获得 <Id> 的值,其中 <CategoriesUrl>cars

现在我这样做

1) $xml = simplexml_load_file( filename.xml' );

2) 然后遍历所有文件

foreach($xml->children() as $subcategory){
  if( trim($subcategory->OneSubcategory->CategoriesUrl) == 'cars' ){
  $id = trim($subcategory->OneSubcategory->Id);
  }
}

是否可以不循环获取值,如mysql SELECT Id WHERE CategoriesUrl = 'cars'?

更新

基于此http://www.tuxradar.com/practicalphp/12/3/3#null

$id = $xml->xpath('Categories/OneSubcategory/Id');得到所有Id

的数组

尝试过$id = $xml->xpath('Categories/OneSubcategory/Id[CategoriesUrl="cars"]'); 获取空数组

哪里不对?

似乎这是一个解决方案

$id = $xml->xpath('Categories/OneSubcategory[CategoriesUrl="cars"]/Id');

由于 CategoriesUrlId 是兄弟姐妹,因此查询似乎不正确。如果您不想循环,则只需将索引显式设置为零即可获取第一个值。

$query = "//Id[following-sibling::CategoriesUrl[text() = 'cars']]";
$nodes = $xml->xpath($query);
if(count($nodes) > 0) { // if found
    // get one
    $id = $nodes[0];
    echo $id;

    // if you want to loop
    // foreach($nodes as $node) { // loop all results
    //  $id = (string) $node;
    //  echo $id;
    // }
}

如果您想要找到所有结果,那么只需使用 foreach。