2015-08-02 1 views
1

У меня есть этот прекрасный фрагмент текста, найденный внутри элемента XML, и вы хотите преобразовать его в простой массив, XML - от wikia.com.Создайте простой PHP-массив из этого текста

массив будет что-то вроде этого:

card name => [Martial] Ares, character name => Ares, release_date => May 1 2013 and so on.. 

Я пробовал все виды не взрывается и взрываются вариации, но не повезло .. Это один получил меня в тупик ..

|card name=[Martial] Ares 
|character name=Ares 
|release_date=May 1 2013 
|image 1=MartialAres5.jpg 
|rarity 1=Super Special Rare 
|pwr req 1=28 
|sale price 1=94200 
|max card lv 1=60 
|max mastery lv 1=40 
|quote 1=Ares prefers weapons that were used during the age of Greek myth: sword, axe, and spear. But he can use any weapon expertly, and turn most ordinary objects into lethal weapons. 
|base atk 1=2440 
|base def 1=2650 
|max atk 1=7015 
|max def 1=7613 
|mastery bonus atk 1=915 
|mastery bonus def 1=993 
|image 2=MartialAres6.jpg 
|rarity 2=Ultimate Rare 
|sale price 2=188400 
|max mastery lv 2=200 
|quote 2=Next time I see Hercules, We're going to have a steel conversation. It's about time for him to answer for massacring my Stymphalian Birds. 
|max atk 2=9822 
|max def 2=10660 
|mastery bonus atk 2=1098 
|mastery bonus def 2=1192 
|alignment=Bruiser 
|ability=Warhawk 
|gender=Male 
|usage=Average 
|faction=Super Hero 
|effect=Significantly harden DEF of your Bruisers. 
|centretrait=None 

Код я пробовал:

if (file_exists('card.xml')) { 
    $xml = simplexml_load_file('card.xml'); 


    $text = $xml->page->revision->text; 
    $newtext = explode('|', $text); 
    foreach($newtext as $newnewtext) { 
     $newtext2 = explode('=', $newnewtext); 
     print_r($newtext2); 

    } 


} else { 
    exit('Failed to open card.xml.'); 
} 
+0

взрывается на трубе \ разрыв линии, петля, взорваться на равных –

+0

Это фрагмент того, что дает мне 'Array ([0] => {{Карта Infobox (2)) Array ([0] => имя карты [1] => [Martial] Ares) Array ([0] => имя персонажа [1] => Ares) ' – CodeX

+1

Редактировать вопрос с кодом пробовал –

ответ

5

по запросу:

<?php 
$file="|card name=[Martial] Ares 
|character name=Ares 
|release_date=May 1 2013 
|image 1=MartialAres5.jpg 
|rarity 1=Super Special Rare 
|pwr req 1=28 
|sale price 1=94200 
|max card lv 1=60 
|max mastery lv 1=40 
|quote 1=Ares prefers weapons that were used during the age of Greek myth: sword, axe, and spear. But he can use any weapon expertly, and turn most ordinary objects into lethal weapons. 
|base atk 1=2440 
|base def 1=2650 
|max atk 1=7015 
|max def 1=7613 
|mastery bonus atk 1=915 
|mastery bonus def 1=993 
|image 2=MartialAres6.jpg 
|rarity 2=Ultimate Rare 
|sale price 2=188400 
|max mastery lv 2=200 
|quote 2=Next time I see Hercules, We're going to have a steel conversation. It's about time for him to answer for massacring my Stymphalian Birds. 
|max atk 2=9822 
|max def 2=10660 
|mastery bonus atk 2=1098 
|mastery bonus def 2=1192 
|alignment=Bruiser 
|ability=Warhawk 
|gender=Male 
|usage=Average 
|faction=Super Hero 
|effect=Significantly harden DEF of your Bruisers. 
|centretrait=None"; 


$x=explode("\n",$file); 
$out=array(); 
foreach($x as $each){ 
    $xx=explode('=',$each); 
$out[ltrim($xx[0],'|')]=$xx[1]; 
} 
echo '<pre>'; 
print_r($out); 

рабочая демонстрация: http://codepad.viper-7.com/3BkXD6

0

Это должно работать для вас:

explode() Ваша строка новой строки. Затем пройдите через каждый элемент с array_map() и взорвите substr() со смещением 1 знаком равенства.

В конце просто используйте array_column(), чтобы использовать первый столбец как значение и столбец 0 в качестве ключа.

$arr = array_column(array_map(function($v){ 
    return explode("=", substr($v, 1)); 
}, explode(PHP_EOL, $str)), 1, 0); 

print_r($arr); 
0

@ Дагон правильный. Вот как может выглядеть реализация:

<?php 
$keyvalues = array(); 
$text = file_get_contents('path/to/your/file'); 
$rows = explode('|',$text); 
foereach($rows as $row) { 
    if (strpos($row,'=')) { 
     $kv = array_map('trim',explode('=',$row)); 
     $keyvalues[ $kv[0] ] = $kv[1]; 
    } 
} 
?> 
+0

Я получаю ошибку' Undefined offset: 1' – CodeX

+0

try array_filter ($ rows = explode ('|', $ text)); – RamRaider

+0

это, вероятно, бросается на пустые строки. Я обновил код, чтобы не пытаться анализировать пустые строки, используя 'if (strpos ($ row, '=')) {...}' –

0

Во-первых, я бы разделил строку на '|' charater.

$ parts = explode ("|", $ str);

Это приведет к массиву, как следующее:

Array 
    (
     [0] => 
     [1] => card name=[Martial] Ares 

     [2] => character name=Ares 

     [3] => release_date=May 1 2013 

     [4] => image 1=MartialAres5.jpg 

     [5] => rarity 1=Super Special Rare 

     [6] => pwr req 1=28 

     [7] => sale price 1=94200 

     [8] => max card lv 1=60 

     [9] => max mastery lv 1=40 

     [10] => quote 1=Ares prefers weapons that were used during the age of Greek myth: sword, axe, and spear. But he can use any weapon expertly, and turn most ordinary objects into lethal weapons. 

     [11] => base atk 1=2440 

     [12] => base def 1=2650 

     [13] => max atk 1=7015 

     [14] => max def 1=7613 

     [15] => mastery bonus atk 1=915 

     [16] => mastery bonus def 1=993 

     [17] => image 2=MartialAres6.jpg 

     [18] => rarity 2=Ultimate Rare 

     [19] => sale price 2=188400 

     [20] => max mastery lv 2=200 

     [21] => quote 2=Next time I see Hercules, We're going to have a steel conversation. It's about time for him to answer for massacring my Stymphalian Birds. 

     [22] => max atk 2=9822 

     [23] => max def 2=10660 

     [24] => mastery bonus atk 2=1098 

     [25] => mastery bonus def 2=1192 

     [26] => alignment=Bruiser 

     [27] => ability=Warhawk 

     [28] => gender=Male 

     [29] => usage=Average 

     [30] => faction=Super Hero 

     [31] => effect=Significantly harden DEF of your Bruisers. 

     [32] => centretrait=None 
    ) 

Далее, я бы цикл по массиву и разделить каждую строку на «=» характер и построить ассоциативный массив из кусочков.

//First remove the first empty element from the array. 
    array_shift($parts); 

    $finalArray = array(); 
    foreach($parts as $part) 
    { 
     $b = explode("=", $part); 
     $finalArray[$b[0]] = $b[1]; 
    } 

Это должно привести к структуре, которую вы ищете.

Array 
(
    [card name] => [Martial] Ares 

    [character name] => Ares 

    [release_date] => May 1 2013 

    [image 1] => MartialAres5.jpg 

    [rarity 1] => Super Special Rare 

    [pwr req 1] => 28 

    [sale price 1] => 94200 

    [max card lv 1] => 60 

    [max mastery lv 1] => 40 

    [quote 1] => Ares prefers weapons that were used during the age of Greek myth: sword, axe, and spear. But he can use any weapon expertly, and turn most ordinary objects into lethal weapons. 

    [base atk 1] => 2440 

    [base def 1] => 2650 

    [max atk 1] => 7015 

    [max def 1] => 7613 

    [mastery bonus atk 1] => 915 

    [mastery bonus def 1] => 993 

    [image 2] => MartialAres6.jpg 

    [rarity 2] => Ultimate Rare 

    [sale price 2] => 188400 

    [max mastery lv 2] => 200 

    [quote 2] => Next time I see Hercules, We're going to have a steel conversation. It's about time for him to answer for massacring my Stymphalian Birds. 

    [max atk 2] => 9822 

    [max def 2] => 10660 

    [mastery bonus atk 2] => 1098 

    [mastery bonus def 2] => 1192 

    [alignment] => Bruiser 

    [ability] => Warhawk 

    [gender] => Male 

    [usage] => Average 

    [faction] => Super Hero 

    [effect] => Significantly harden DEF of your Bruisers. 

    [centretrait] => None 
) 
+0

На самом деле это привело к простому тексту, который выглядит как классный, но не что мне нужно – CodeX

+0

@CodeX -It приводит к массиву php. Я просто запустил print_r, чтобы вы увидели, что создали правильную структуру. Если вы запустите код, вы увидите, что переменная $ finalArray IS AN ARRAY со структурой, которую вы просили. – dlporter98

+0

Когда я это делаю, он выводится как список значений, im 'print_r ($ finalArray [$ b [0]] = $ b [1]);' – CodeX

0

С минимальной проверкой ошибок:

$text = explode('|', $text); 
$result = array(); 
foreach ($text as $entry) { 
    if ($entry) { 
     $entry = explode('=', $entry); 
     $result[$entry[0]] = $entry[1]; 
    } 
} 
1

Самым простым и эффективным способом для достижения этой цели является использованием регулярных выражений.Учитывая, что $ строка содержит данные, выполните следующие действия:

preg_match_all('/^\|(?<key>[^=]+)=(?<value>.*)$/m', $string, $matches); 
print_r(array_combine($matches['key'], $matches['value'])); 

Для данных вы предоставили в качестве примера вы получите:

Array 
(
    [card name] => [Martial] Ares 
    [character name] => Ares 
    [release_date] => May 1 2013 
    [image 1] => MartialAres5.jpg 
    [rarity 1] => Super Special Rare 
    [pwr req 1] => 28 
    [sale price 1] => 94200 
    [max card lv 1] => 60 
    [max mastery lv 1] => 40 
    ...and so on 
) 
Смежные вопросы