使用XML仅显示具有特定属性的产品

XML file contains for about 10 000 products with different 'cat_top' attribute. I need to parse only products that belong to a category "PC".

<product id="6055551" cat="Motherboards" cat_top="PC">
</product>
<product id="6666691" cat="Motherboards" cat_top="PC">
</product>
<product id="6044391" cat="Motherboards" cat_top="PC"> 
</product>
<product id="6041391" cat="iPad" cat_top="Apple"> 
</product>
<product id="6041391" cat="iPhone" cat_top="Apple"> 
</product>
<product id="6423391" cat="iPad" cat_top="Apple"> 
</product>
<product id="6067391" cat="iPhone" cat_top="Apple">
</product>

This is my code:

<?php

if (file_exists('xml_im.xml')) {
    $xml = simplexml_load_file('xml_im.xml');
} else {
    exit('Не удалось открыть файл xml_im.xml.');
}    

foreach($xml->product as $product) {

    $name = $product['id'];
    $cat = $product['cat'];
    echo $name, " " , $cat , " ";   

}
?>

How about you just continue the loop if it is not a 'PC':

<?php

if (file_exists('xml_im.xml')) {
    $xml = simplexml_load_file('xml_im.xml');
} else {
    exit('Не удалось открыть файл xml_im.xml.');
}

foreach ($xml->product as $product) {

    $cat_top = (string)$product['cat_top'];
    if ($cat_top !== 'PC') continue;

    $name = $product['id'];
    $cat = $product['cat'];
    echo $name, " ", $cat, " ";

}
?>

You can use an xpath to obtain an array of <product>s that match:

$xml->xpath('//product[@cat_top = "PC"]')

If you wanted to loop through them as you have done in the question, you could do this:

foreach ($xml->xpath('//product[@cat_top = "PC"]') as $product) {
    echo "{$product['id']} {$product['cat']}";
}