Как скрыть пустые теги в XML?

(Ответов: 13, Просмотров: 3065)
Страница 1 из 2 12 Последняя
  1. Senior Member
    • Регистрация: 05.11.2010
    • Сообщений: 115
    • Репутация: 17
    PHP Code:
    <area>
    <value>'.$row['squarefeet'].'</value>
    <unit>'.($row['squarefeet']!='' ? 'кв.м' : '').'</unit>
    </area>
    В сгенерированном виде выглядит:

    Если есть данные:

    <area>
    <value>200</value>
    <unit>кв.м</unit>
    </area>

    Если пусто:
    HTML Code:

    <area>
    <value></value>
    <unit></unit>

    </area>
    И вот имеем ошибка:

    Статус XSD:
    Error: cvc-pattern-valid: Value '' is not facet-valid with respect to pattern '[0-9 ]+((\.|,)[0-9]+)?' for type 'loose-float'. Line: 31 Error: cvc-type.3.1.3: The value '' of element 'value' is not valid. Line: 31 Error: cvc-type.3.1.3: The value '' of element 'value' is not valid. Line: 35
    Предполагаю, что это из-за пустоты в теге. Как сделать, чтоб тег был виден только если: row['squarefeet']!='' ?
    • 0
  2. Дипломник
    • Регистрация: 06.11.2010
    • Сообщений: 135
    • Записей в дневнике: 8
    • Репутация: 9
    Можно так попробовать, xml узел выведется только если строка не пустая

    function getNode($squarefeet) {
    if (strlen($squarefeet) == 0) return '';
    else return "<area>
    <value>".$squarefeet."</value>
    <unit>".($squarefeet!='' ? 'кв.м' : '')."</unit>
    </area> ";
    }

    echo getNode($row['squarefeet']);
    • 0
  3. Senior Member
    • Регистрация: 05.11.2010
    • Сообщений: 115
    • Репутация: 17
    а куда это вставить?
    • 0
  4. Member Аватар для AMS
    • Регистрация: 06.11.2010
    • Сообщений: 53
    • Репутация: 15
    Цитата Сообщение от konstanta Посмотреть сообщение
    а куда это вставить?
    . у вас генерация идёт в цикле, а в $row находятся поля из БД? cветите код
    • 0
  5. Senior Member
    • Регистрация: 05.11.2010
    • Сообщений: 115
    • Репутация: 17
    Цитата Сообщение от AMS Посмотреть сообщение
    . у вас генерация идёт в цикле, а в $row находятся поля из БД? cветите код
    <?php

    mysql_connect("localhost", "********", "*****"); //db_login - имя и пароль пользователя в mysql
    mysql_select_db("*******") or die ("Unable to select database"); // имя БД
    $q=mysql_query("SET CHARACTER SET UTF8");
    $myItemid = 34;
    $er_imagedirectory = 'ezrealty';



    # Don't allow direct linking
    // defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

    // global $database, $mainframe, $my, $Itemid, $mosConfig_absolute_path, $mosConfig_MetaDesc;

    //$er_rssname = stripslashes($er_rssname);

    // set the file content type and character set
    header("Content-Type: text/xml;charset=UTF-8");
    $mydate = date("Y-m-d\TH:i:s+03:00");


    //$phpversion = phpversion();

    //set the beginning of the xml file
    ECHO <<<END
    <?xml version="1.0" encoding="UTF-8"?>
    <realty-feed xmlns="http://webmaster.yandex.ru/schemas/feed/realty/2010-06">
    <generation-date>$mydate</generation-date>
    END;


    // Find EZ Realty Itemid from the menu table
    /*
    $query = "SELECT * from #__menu"
    . "\n WHERE link = 'index.php?option=com_ezrealty'"
    ;
    $database->setQuery( $query );
    $id = $database->loadResult();
    $Itemid = $id;
    */

    # Do the main database query
    $query = "SELECT a.price, a.freq, a.cid, a.smalldesc, a.type, a.image1, a.address2, a.street_num, a.bedrooms, squarefeet, a.totalrooms, a.bathrooms, a.frontage, a.depth, a.custom6, a.custom7, a.custom8, a.primaryschool, a.preschool, a.schooldist, a.id, a.image1desc, a.listdate, cc.name AS category, ee.ezcity AS proploc, ee.ezcity_desc AS ezdesc, dd.name AS statename, bb.name AS countryname, u.mid AS mid, u.dealer_name AS dealer_name, u.dealer_company AS dealer_company, u.dealer_phone AS dealer_phone,
    u.dealer_mobile AS dealer_mobile, u.dealer_email AS dealer_email, u.dealer_image AS dealer_image, u.dealer_type AS dealer_type FROM jos_ezrealty as a"
    . "\n LEFT JOIN jos_ezrealty_catg AS cc ON cc.id = a.cid"
    . "\n LEFT JOIN jos_ezrealty_locality AS ee ON ee.id = a.locid"
    . "\n LEFT JOIN jos_ezrealty_state AS dd ON dd.id = a.stid"
    . "\n LEFT JOIN jos_ezrealty_country AS bb ON bb.id = a.cnid"
    . "\n LEFT JOIN jos_ezrealty_profile AS u ON u.mid = a.owner"
    . "\n WHERE a.published=1 AND cc.published=1 AND a.stid=2 AND (a.cid=1 OR a.cid=20 OR a.cid=21 OR a.cid=23 OR a.cid=27) AND listdate > NOW() - INTERVAL 180 DAY"
    . "\n ORDER BY a.id DESC"
    ;

    $database = mysql_query($query) or die(mysql_error());

    //Make a loop to create the feed

    while ($row = mysql_fetch_assoc ($database)) {
    // Clean up the price format for use in rss feeds

    $number = $row['price'];
    $formatted_price = number_format($number, 0,",","");

    // Clean up the short description for use in rss feeds

    $row['smalldesc'] = preg_replace(array('/&/', '/</', '/>/', '/"/'), array('&amp;', '&lt;', '&gt;', '&quot;'), $row['smalldesc']);
    $row['smalldesc'] = str_replace( "'", "'", $row['smalldesc']);

    $row['statename'] = preg_replace(array('/&/', '/</', '/>/', '/"/'), array('&amp;', '&lt;', '&gt;', '&quot;'), $row['statename']);
    $row['statename'] = str_replace( "'", "'", $row['statename']);

    $row['address2'] = preg_replace(array('/&/', '/</', '/>/', '/"/'), array('&amp;', '&lt;', '&gt;', '&quot;'), $row['address2']);
    $row['address2'] = str_replace( "'", "'", $row['address2']);

    $row['street_num'] = preg_replace(array('/&/', '/</', '/>/', '/"/'), array('&amp;', '&lt;', '&gt;', '&quot;'), $row['street_num']);
    $row['street_num'] = str_replace( "'", "'", $row['street_num']);

    $row['image1desc'] = preg_replace(array('/&/', '/</', '/>/', '/"/'), array('&amp;', '&lt;', '&gt;', '&quot;'), $row['image1desc']);
    $row['image1desc'] = str_replace( "'", "'", $row['image1desc']);

    $row['dealer_company'] = preg_replace(array('/&/', '/</', '/>/', '/"/'), array('&amp;', '&lt;', '&gt;', '&quot;'), $row['dealer_company']);
    $row['dealer_company'] = str_replace( "'", "'", $row['dealer_company']);

    $row['dealer_phone'] = preg_replace(array('/&/', '/</', '/>/', '/"/'), array('&amp;', '&lt;', '&gt;', '&quot;'), $row['dealer_phone']);
    $row['dealer_phone'] = str_replace( "'", "'", $row['dealer_phone']);

    $row['frontage'] = preg_replace(array('/&/', '/</', '/>/', '/"/'), array('&amp;', '&lt;', '&gt;', '&quot;'), $row['frontage']);
    $row['frontage'] = str_replace( "'", "'", $row['frontage']);

    $row['depth'] = preg_replace(array('/&/', '/</', '/>/', '/"/'), array('&amp;', '&lt;', '&gt;', '&quot;'), $row['depth']);
    $row['depth'] = str_replace( "'", "'", $row['depth']);

    // Clean up the category name for use in rss feeds

    $row['cid2'] = preg_replace(array('/21/', '/20/', '/23/', '/27/', '/1/'), array('коммерческая', 'дом', 'участок', 'комната', 'квартира'), $row['cid']);
    $row['type'] = preg_replace(array('/1/', '/2/'), array('продажа', 'аренда'), $row['type']);
    $row['property-type'] = preg_replace(array('/коммерческая/', '/дом/', '/участок/', '/комната/', '/квартира/'), array('коммерческая', 'жилая', 'коммерческая', 'жилая', 'жилая'), $row['cid2']);
    $row['dealer_type'] = preg_replace(array('/1/', '/2/', '/3/', '/4/', '/5/'), array('агентство', 'владелец', 'агентство', 'владелец', 'агентство'), $row['dealer_type']);


    // display an item

    echo '
    <offer internal-id="'.$row['id'].'">
    <type>'.$row['type'].'</type>
    <property-type>'.$row['property-type'].'</property-type>
    <category>'.$row['cid2'].'</category>
    <url>http://******/index.php?option=com_ezrealty&amp;Itemid='.$myItem id.'&amp;task=detail&amp;id='.$row['id'].'</url>
    <creation-date>'.$row['listdate'].'T00:00:00+10:00</creation-date>
    <location>
    <country>Россия</country>
    <region>******</region>
    <locality-name>******</locality-name>
    <sub-locality-name>'.$row['proploc'].'</sub-locality-name>
    <address>'.$row['address2'].' '.($row['street_num']!=='0' ? $row['street_num'] : '').'</address>
    </location>
    <sales-agent>
    <name>'.$row['dealer_name'].'</name>
    <phone>'.$row['dealer_phone'].' '.$row['dealer_mobile'].'</phone>
    <category>'.$row['dealer_type'].'</category>
    <organization>'.$row['dealer_company'].'</organization>
    <partner>**********</partner>
    </sales-agent>
    <price>
    <value>'.$formatted_price.'</value>
    <currency>RUB</currency>
    <unit>'.($row['freq']==1 ? 'кв.м' : '').'</unit>
    </price>
    <image>'.($row['image1']!='' ? 'http://***********/components/com_ezrealty/ezrealty/'.$row['image1'] : '').'</image>
    <area>
    <value>'.$row['squarefeet'].'</value>
    <unit>'.($row['squarefeet']!='' ? 'кв.м' : '').'</unit>
    </area>
    <living-space>
    <value>'.$row['totalrooms'].'</value>
    <unit>'.($row['totalrooms']!='' ? 'кв.м' : '').'</unit>
    </living-space>
    <kitchen-space>
    <value>'.$row['bathrooms'].'</value>
    <unit>'.($row['bathrooms']!='' ? 'кв.м' : '').'</unit>
    </kitchen-space>
    <description>'.$row['smalldesc'].'</description>
    <quality>'.$row['custom8'].'</quality>
    <rooms>'.($row['bedrooms']!=='0' ? $row['bedrooms'] : '').'</rooms>
    <rooms-type>'.($row['schooldist']!=='0' ? $row['schooldist'] : '').'</rooms-type>
    <balcony>'.($row['primaryschool']!=='0' ? $row['primaryschool'] : '').'</balcony>
    <bathroom-unit>'.$row['preschool'].'</bathroom-unit>
    <floor>'.$row['frontage'].'</floor>
    <floors-total>'.$row['depth'].'</floors-total>
    <building-type>'.$row['custom6'].'</building-type>
    <building-series>'.$row['custom7'].'</building-series>
    </offer>
    ';

    }

    // Close the database

    mysql_close();

    // And end the xml file

    ECHO <<<END
    </realty-feed>
    END;

    ?>
    такой
    • 0
  6. Дипломник
    • Регистрация: 06.11.2010
    • Сообщений: 135
    • Записей в дневнике: 8
    • Репутация: 9
    У вас так

    <area>
    <value>'.$row['squarefeet'].'</value>
    <unit>'.($row['squarefeet']!='' ? 'кв.м' : '').'</unit>
    </area>
    а нуэнотак:


    <area>
    <value>'.$row['squarefeet'].'</value>
    '.($row['squarefeet']!='' ?'<unit>кв.м</unit>' : '').'
    </area>
    тогда элемент <unit> выводится не будет
    • 0
  7. Senior Member
    • Регистрация: 05.11.2010
    • Сообщений: 115
    • Репутация: 17
    Тоесть нужно закрыть все теги?
    • 0
  8. Banned
    • Регистрация: 06.11.2010
    • Сообщений: 79
    • Репутация: 10
    Цитата Сообщение от konstanta Посмотреть сообщение
    Тоесть нужно закрыть все теги?
    Вам дали функцию у которой параметр $row['squarefeet'] выходной , вставляйте эту функцию в самое начало,

    $er_imagedirectory = 'ezrealty';
    Далее в теле программы, вместо

    <area>
    <value>'.$row['squarefeet'].'</value>
    <unit>'.($row['squarefeet']!='' ? 'кв.м' : '').'</unit>
    </area>
    Вы пишите:

    getNode($row['squarefeet']);
    Функцию надо оптимизировать под Ваш скрипт и заменить вывод во всех необходимых местах.
    • 0
  9. Senior Member
    • Регистрация: 05.11.2010
    • Сообщений: 115
    • Репутация: 17
    getNode($row['squarefeet']);
    появляется ошибка когда вставляю.
    • 0
  10. Дипломник
    • Регистрация: 06.11.2010
    • Сообщений: 135
    • Записей в дневнике: 8
    • Репутация: 9
    какая именно ошибка, и куда вы вставляете вызов функции?
    • 0
Страница 1 из 2 12 Последняя

Похожие темы

Темы Раздел Ответов Последний пост
Теги / метки на блоге полезны?
Блоги 11 14.02.2010 22:12
Как скрыть ссылочки :)
Вопросы от новичков 1 27.10.2009 18:37
WordPress динамит теги
Прочее 12 09.09.2009 18:03

Интересные темы

вывод данных с таблицы wordpress

Читай в этой теме, как организовать вывод данных в нужные поля с таблицы для wordpress.

У кого попросить инвайт?

Вы можете попросить инвайт у любого модератора:

Информеры