помогите получить данные из xml в php - Форум успешных вебмастеров - GoFuckBiz.com
 
 
Форум успешных вебмастеров - GoFuckBiz.com

  Форум успешных вебмастеров - GoFuckBiz.com > Бизнес-решения > Скрипты, программы и технические решения
Дата
USD/RUB93.4409
BTC/USD64146.8600
Скрипты, программы и технические решения Обсуждаем скрипты, программы и новые технологии.

Закрытая тема
Опции темы Опции просмотра
Старый 10.12.2010, 00:16   #1
rulfer
очень злой, очень плохой
 
Регистрация: 09.04.2007
Сообщений: 230
Бабло: $19860
По умолчанию помогите получить данные из xml в php

Есть вот такой вот xml файл

PHP код:
<timeline-menu>
   <
timeline-item id="1" processing-order="9">
      <
name></name>

      <
exhibitions>
         <
exhibition id="11">
            <
date></date>
            <
title></title>
            <
annotation></annotation>
            <
image id="111"><label></label><filepath size="a"></filepath><filepath size="b"></filepath><filepath size="c"></filepath></image>
         </
exhibition>
      </
exhibitions>
   </
timeline-item>

   <
timeline-item id="2" processing-order="9">
      <
name></name>
      <
exhibitions>

         <
exhibition id="21">
            <
date></date>
            <
title></title>
            <
annotation></annotation>
            <
image id="211"><label></label><filepath size="a"></filepath><filepath size="b"></filepath><filepath size="c"></filepath></image>
         </
exhibition>

         <
exhibition id="22">
            <
date></date>
            <
title></title>
            <
annotation></annotation>
            <
image id="222"><label></label><filepath size="a"></filepath><filepath size="b"></filepath><filepath size="c"></filepath></image>
         </
exhibition>

      </
exhibitions>
   </
timeline-item>

и ещё много много данных

</timeline-menu
подскажите, кто разбирается в чтении xml из php. как получить данные из этого xml

напрмиер вот так у меня получается получить array с данными поля name

PHP код:
$xml simplexml_load_string($text);
print_r($xml->xpath("/timeline-menu/timeline-item/name")); 
дальше тупняк, а мне необходимо как то вытаскивать

из "timeline-item" значение id="1" и processing-order="9"

понять сколько внутри каждого блока <exhibitions> вложенных <exhibition> и получить их id и данные из вложенных блоков.

подскажите как сделать.
rulfer вне форума  
Старый 10.12.2010, 02:02   #2
splogger
Senior Member
 
Регистрация: 05.10.2007
Сообщений: 296
Бабло: $45450
По умолчанию

http://www.php.net/manual/en/domelem...bute.php#79074
__________________
b31c09c139d9f79bb3ef1b799c48f33c
splogger вне форума  
Старый 10.12.2010, 08:34   #3
rulfer
очень злой, очень плохой
 
Регистрация: 09.04.2007
Сообщений: 230
Бабло: $19860
ТС -->
автор темы ТС По умолчанию

Цитата:
Сообщение от splogger Посмотреть сообщение
спасибо, но к сожалению, я вообще ничего не понял
rulfer вне форума  
Старый 10.12.2010, 08:47   #4
rulfer
очень злой, очень плохой
 
Регистрация: 09.04.2007
Сообщений: 230
Бабло: $19860
ТС -->
автор темы ТС По умолчанию

PHP код:
foreach ($xml->xpath('/timeline-menu/timeline-item/exhibitions') as $exibitions) {
    <? print_r($exibitions); ?>
    foreach ($exibitions as $exi) {
        //print_r($exi);
        ?>
        <?=$exi['id'];?>
        <?=$exi->title;?>
        <?=$exi->annotation;?>
        <? print_r($exi->image);?>
        <?
    
}
}
методом тыка пришёл вот к таким вот конструкциям и вроде мне это подходит.
rulfer вне форума  
Старый 10.12.2010, 11:48   #5
Drunk Monk
Je suis moine ivre
 
Аватар для Drunk Monk
 
Регистрация: 03.03.2009
Сообщений: 15,268
Бабло: $797172957
По умолчанию

PHP код:
function xml2array($contents$get_attributes=1) {
/**
* xml2array() will convert the given XML text to an array in the XML structure.
* Link: http://www.bin-co.com/php/scripts/xml2array/
* Arguments : $contents - The XML text
* $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
* Return: The parsed XML in an array form.
*/
if(!$contents) return array();

if(!
function_exists('xml_parser_create')) {
//print "'xml_parser_create()' function not found!";
return array();
}
//Get the XML parser of PHP - PHP must have this module for the parser to work
$parser xml_parser_create();
xml_parser_set_option$parserXML_OPTION_CASE_FOLDING);
xml_parser_set_option$parserXML_OPTION_SKIP_WHITE);
xml_parse_into_struct$parser$contents$xml_values );
xml_parser_free$parser );

if(!
$xml_values) return;//Hmm...

//Initializations
$xml_array = array();
$parents = array();
$opened_tags = array();
$arr = array();

$current = &$xml_array;

//Go through the tags.
foreach($xml_values as $data) {
unset(
$attributes,$value);//Remove existing values, or there will be trouble

//This command will extract these variables into the foreach scope
// tag(string), type(string), level(int), attributes(array).
extract($data);//We could use the array by itself, but this cooler.

$result '';
if(
$get_attributes) {//The second argument of the function decides this.
$result = array();
if(isset(
$value)) $result['value'] = $value;

//Set the attributes too.
if(isset($attributes)) {
foreach(
$attributes as $attr => $val) {
if(
$get_attributes == 1$result['attr'][$attr] = $val//Set all the attributes in a array called 'attr'
/** :TODO: should we change the key name to '_attr'? Someone may use the tagname 'attr'. Same goes for 'value' too */
}
}
} elseif(isset(
$value)) {
$result $value;
}

//See tag status and do the needed.
if($type == "open") {//The starting of the tag "
$parent[$level-1] = &$current;

if(!
is_array($current) or (!in_array($tagarray_keys($current)))) { //Insert New tag
$current[$tag] = $result;
$current = &$current[$tag];

} else { 
//There was another element with the same tag name
if(isset($current[$tag][0])) {
array_push($current[$tag], $result);
} else {
$current[$tag] = array($current[$tag],$result);
}
$last count($current[$tag]) - 1;
$current = &$current[$tag][$last];
}

} elseif(
$type == "complete") { //Tags that ends in 1 line "
//See if the key is already taken.
if(!isset($current[$tag])) { //New Key
$current[$tag] = $result;

} else { 
//If taken, put all things inside a list(array)
if((is_array($current[$tag]) and $get_attributes == 0)//If it is already an array…
or (isset($current[$tag][0]) and is_array($current[$tag][0]) and $get_attributes == 1)) {
array_push($current[$tag],$result); // …push the new element into that array.
} else { //If it is not an array…
$current[$tag] = array($current[$tag],$result); //…Make it an array using using the existing value and the new value
}
}

} elseif(
$type == 'close') { //End of tag "
$current = &$parent[$level-1];
}
}

return(
$xml_array);

Drunk Monk вне форума  
Старый 10.12.2010, 16:58   #6
rulfer
очень злой, очень плохой
 
Регистрация: 09.04.2007
Сообщений: 230
Бабло: $19860
ТС -->
автор темы ТС По умолчанию

то что надо. спасибо.
rulfer вне форума  
Старый 10.12.2010, 17:35   #7
JackSoft
Бабло победит зло
 
Аватар для JackSoft
 
Регистрация: 20.06.2008
Сообщений: 2,579
Бабло: $346045
По умолчанию

Регулярку пользуй. симплхмл очень привередлив.
__________________
"Одно Касание/Touch File" - безопасный обмен файлами "TFUtils" - набор утилит TouchFile "TF Screenshots" - заменим Gyazo безопасным аналогом
JackSoft вне форума  
Старый 11.12.2010, 07:36   #8
chesser
автоматизирую интернеты
 
Аватар для chesser
 
Регистрация: 05.07.2009
Адрес: chesser.ru
Сообщений: 3,362
Бабло: $470735
По умолчанию

simplexml - не используйте вы это говно примитивное
в php есть два цивилизованных метода парсинга xml - SAX парсер и DOM
первый: долгий, почти не имеет готовых вспомогательных функций(ну кроме xml_ parse_ into_ struct - но она редко когда удобна), т.е. почти все надо описывать самому, зато потребляет мало памяти, универсальный в плане расширения функционала - сам пишешь свои функции парсинга.
второй типа парсеров основан на постороении дом модели, т.е. требует много памяти, быстр и много готовых функций и расширений, тот же xpath - очень удобен для хождения по дом-дереву

регулярками парсить XML конечно можно, но это слишком универсально, как и кодить на асме под вин.
XML - это уже набор правил, и лучше использовать технологии, которые уже работают по этим правилам. К тому же не всегда знаешь наперед, какой дополнительный функционал понадобиться: Сейчас нужен только первый exhibition, завтра первых два, потом все понадобятся внутри конкретного timeline-item - на регулярках глаза сломаешь, а дом быстро построится, даже сломанный
__________________
USA и NL серверы и VPS | wiki | блог | Drupal | NginxТДС
Ave, Google, morituri te salutant! © chesser
chesser вне форума