1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
|
// Retourne un array avec les clés = les tags
// et les values = les données des tags d'un <item>
// L'item est repéré par son id
function getItemById($id, $xmlstr) {
$r = '~<id>'.$id.'</id>(.+?)</item>~s';
if (preg_match($r, $xmlstr, $ar))
return parseItem($ar[1]);
return array();
}
// Retourne un array avec les clés = les tags
// et les values = les données des tags d'un <item>
// L'item est repéré par sa position de haut en bas
// 1er item: 1, 2iem 2 etc
function getItemByPos($pos, $xmlstr) {
$r = '~(?:<item>.+?</item>\s*){'.($pos-1).'}\s*<item>(.+?)</item>~s';
if (preg_match($r, $xmlstr, $ar))
return parseItem($ar[1]);
return array();
}
// Fonction utilisée par les 2 premières
function parseItem($str) {
$array = array();
$r = '~<([^>]+)>(.+?)</\1>~';
if (preg_match_all($r, $str, $ar)) {
//uniquement en php5
//$array = array_combine($ar[1], $ar[2]);
for ($i = 0, $e = count($ar[1]); $i < $e; ++$i) {
$array[$ar[1][$i]] = $ar[2][$i];
}
}
return $array;
}
// Retourne une chaine xml téléchargée
function getXML($url) {
$str = '';
if (($f = fopen($url, 'r')) !== FALSE) {
while (!feof($f)) $str .= fread($f, 4096);
fclose($f);
}
return $str;
}
// Code de test. On chope le 3ième item de clubic
$xml = 'http://www.clubic.com/xml/news.xml';
$xmlstr = getXML($xml);
print_r(getItemByPos(3, $xmlstr));
// Pour un autre flux qui à des <id>
// $xml = '...';
// $xmlstr = getXML($xml);
// print_r(getItemById(7, $xmlstr)); |
Partager