PHP从XML属性进行导航

时间:2017-05-21 17:24:51

标签: php arrays xml

我正在尝试使用XML数据库属性进行导航。一些元素具有相同的属性值,但是当我尝试仅在它不起作用时回显该值。我已经尝试过array_key_exist,in_array和array_search而不是一个有效的。现在我有2个三星属性和2个Iphone属性。三星出现了两次,但Iphone只出现过一次。你能帮我吗? PHP:

<?php
        $xml = simplexml_load_file("Database/products.xml");
        $stack = array();
        foreach($xml->Mobile as $phone){
            $attr_value = $phone[0]['model'];
            $attr = (string)$attr_value;
            $link = "ponuda.php?name=".$attr;
            $array_check = array_search($attr, $stack);
            if (!($array_check)) {
                $stack[] = $attr;
                echo '<li><a href=' . $link . '>' . $attr . '</a></li>';
            }
        }
        ?>

XML:

<Products>
    <Mobile model="Samsung">
        <Model>Samsung Galaxy A5</Model>
        <Price>150</Price>
        <Description></Description>
        <Picture></Picture>
        <Screen></Screen>
        <Memory></Memory>
        <Android></Android>
    </Mobile>
    <Mobile model="Samsung">
        <Model>Samsung Galaxy A3</Model>
        <Price>130</Price>
        <Description></Description>
        <Picture></Picture>
        <Screen></Screen>
        <Memory></Memory>
        <Android></Android>
    </Mobile>
<Mobile model="Iphone">
        <Model>Iphone 8</Model>
        <Price>500</Price>
        <Description></Description>
        <Picture></Picture>
        <Screen></Screen>
        <Memory></Memory>
        <Android></Android>
    </Mobile>
    <Mobile model="Iphone">
        <Model>Iphone 8+</Model>
        <Price>450</Price>
        <Description></Description>
        <Picture></Picture>
        <Screen></Screen>
        <Memory></Memory>
        <Android></Android>
    </Mobile>
</Products>

2 个答案:

答案 0 :(得分:1)

您是否以这种方式尝试过in_array

<?php
        $xml = simplexml_load_file("Database/products.xml");
        $stack = array();
        foreach($xml->Mobile as $phone){
            $attr_value = $phone[0]['model'];
            $attr = trim($attr_value);
            $link = "ponuda.php?name=".$attr;
            $array_check = in_array($attr, $stack);
            if (!$array_check) {
                $stack[] = $attr;
                echo '<li><a href=' . $link . '>' . $attr . '</a></li>';
            }
        }

差异分为两行$attr = trim($attr_value);$array_check = in_array($attr, $stack);

答案 1 :(得分:0)

您可以尝试使用array_unique

$xml = simplexml_load_file($url);
$stack = array();
foreach($xml->Mobile as $phone){
    $stack [] = $phone[0]['model'];  
}

echo '<pre>'.   print_r(array_unique($stack),true).'</pre>';

结果

    (
    [0] => SimpleXMLElement Object
        (
            [0] => Samsung
        )

    [2] => SimpleXMLElement Object
        (
            [0] => Iphone
        )

)