XML解析中的条件 - PHP

时间:2014-04-29 06:16:02

标签: php xml parsing

自上次编码以来已经有一段时间了,我有点生疏了。我正在尝试解析xml文件并遇到问题。花了几个小时试图找出问题所在,但没有成功......

PHP代码:

<div id="gallery">
    <?php 
    $cat_img="images/cat.png";
    $logo_path="logos/";

    $file = simplexml_load_file('stores.xml');
    $old_cat="";

    foreach($file->store as $store){
        if($store->cat != $old_cat){
            echo "<img id='cat' src='".$cat_img."'><div id='cat_text'>".$store->cat."</div><br>";
            $old_cat=$store->cat;
        }

        echo "<div id='store'><img id='store_img' src='".$logo_path.$store->logo."' alt='logo'><br>";
        echo "<store_name>".$store->name."</store_name>";
        echo "<phone>".$store->phone."</phone><phone>טל:&nbsp;</phone></div>";
    }
    ?>
</div>

STORES.XML

<?xml version="1.0" encoding="UTF-8"?>

<stores>

    <store><logo>renuar.jpg</logo>
    <name>renuar</name>
    <phone>052-6059962</phone>
    <cat>clothing</cat></store>

    <store><logo>yoop.jpg</logo>
    <name>YOOP</name>
    <phone>08-6601451</phone>
    <cat>clothing</cat></store>

....

</stores>

想法是打印每个商店,当类别更改时,它应该打印类别分隔符并继续打印商店。不知怎的,情况总是如此,我不知道为什么......

P.S 如果有人对如何划分类别有更好的了解,那么我会很高兴听到。

感谢!!!

1 个答案:

答案 0 :(得分:0)

$store->cat将为SimpleXMLElement object,即使具有相同的类别名称,两个对象也不会相同。您需要cast将其string进行比较

(string) $store->cat一样,试试这个:

<?php
$cat_img = "images/cat.png";
$logo_path = "logos/";
$file = simplexml_load_file('test.xml');
$old_cat = "";
foreach ($file->store as $store) {
    if ((string) $store->cat != $old_cat) {
        echo "<img id='cat' src='" . $cat_img . "'><div id='cat_text'>category: " . $store->cat . "</div><br>";
        $old_cat = (string) $store->cat;
    }
    echo "<div id='store'><img id='store_img' src='" . $logo_path . $store->logo . "' alt='logo'><br>";
    echo "<store_name>" . $store->name . "</store_name>";
    echo "<phone>" . $store->phone . "</phone><phone>טל:&nbsp;</phone></div>";
}
?>