2017-10-16 09:20



I'm not so sure about the title, will try to explain in the next lines.

I have an xml file like this :

 <CAR park="3" id="1" bay="0">
    <SITE_NAME>Car Seller 1</SITE_NAME>
    . . .

I am sucessfully iterating through my xml to get all the data. But, I want to be able to filter by bays. I want to do something like

$xml = simplexml_load_file('myfile.xml');
$x = 1;
    foreach($xml as $car) {
    if($car->bay == '0'){
        echo $car->SITE_ID;

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • doubi2228 doubi2228 4年前

    You can use XPath to fetch only the bay 0 cars...

    $bay0 = $xml->xpath('//CAR[@bay="0"]');
    foreach ( $bay0 as $car )   {
        echo $car->SITE_ID.PHP_EOL;

    The XPath statement is simply - any CAR element that has an attribute bay with the value 0 in it.

    In case you need to access attributes in other cases, with SimpleXML - you access them as though they are array elements, so it would be $car['bay'] in the code you had above.

    点赞 评论 复制链接分享