доступ к XML элементам и пространствам имен с новостного сайта с помощью PHP (отредактировано) - PullRequest
0 голосов
/ 22 марта 2020

Я извлек xml содержимое с помощью file_get_contents и попытался SimpleXMLElement, но полученный массив PHP содержит только родительские элементы данных XML.

Вот мой xml файл :

    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
    xmlns:image="http://www.google.com/schemas/sitemap-image/1.1">
<url>
    <loc>
        https://www.lemonde.fr/culture/article/2020/03/22/crise-sanitaire-malgre-les-annonces-du-gouvernement-les-intermittents-du-spectacle-restent-inquiets_6034031_3246.html
    </loc>
    <lastmod>2020-03-22T17:16:47+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T17:16:47+01:00</news:publication_date>
        <news:title>Crise sanitaire : malgré les annonces du gouvernement, les intermittents du spectacle restent
            inquiets
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/20/393/0/4202/2095/1440/720/60/0/b4edd55_cHenKQY0oG4tSBtN-ZWIomUW.jpg
        </image:loc>
        <image:caption>Devant le Palais des festivals, en mai 2019, à Cannes.</image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/climat/article/2020/03/22/l-eau-a-l-epreuve-des-changements-climatiques_6034029_1652612.html
    </loc>
    <lastmod>2020-03-22T16:34:35+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T16:34:35+01:00</news:publication_date>
        <news:title>L’eau à l’épreuve des changements climatiques</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/22/489/0/5300/2650/1440/720/60/0/393a56f_3F3HrswrRMU3J0hrlkkzeI2u.jpg
        </image:loc>
        <image:caption>Une ferme de la région de la Nouvelle-Galles du Sud, le 27 août 2019. L’Australie faisiat
            alors face à une pénurie d’eau sans précédent.
        </image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/journal-blouses-blanches/article/2020/03/22/journal-de-crise-des-blouses-blanches-la-consigne-est-de-se-cacher-quand-le-brancard-passe_6034028_6033712.html
    </loc>
    <lastmod>2020-03-22T16:02:29+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T16:02:29+01:00</news:publication_date>
        <news:title>Journal de crise des blouses blanches : « La cot nsigne est de se cacher quand le brancard passe
            »
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>https://img.lemde.fr/2020/03/21/0/0/1920/960/1440/720/60/0/47f65f2_MMGpM5CMXMxD42fVNqiTPotG.png
        </image:loc>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/politique/article/2020/03/22/coronavirus-olivier-faure-reclame-une-economie-de-guerre-face-a-l-epidemie_6034027_823448.html
    </loc>
    <lastmod>2020-03-22T17:23:13+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T15:59:43+01:00</news:publication_date>
        <news:title>Coronavirus : Olivier Faure réclame une « économie de guerre » face à l’épidémie</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/02/19/206/0/5472/2724/1440/720/60/0/46aadf7_ROMWyKxef0RZ6qlNaCNMtbd0.jpg
        </image:loc>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/afrique/article/2020/03/22/guinee-le-referendum-constitutionnel-et-les-legislatives-troubles-par-des-violences_6034026_3212.html
    </loc>
    <lastmod>2020-03-22T16:19:54+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T15:39:13+01:00</news:publication_date>
        <news:title>Guinée : le référendum constitutionnel et les législatives troublés par des violences
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>https://img.lemde.fr/2020/03/22/460/0/5520/2760/1440/720/60/0/08fb91c_5425067-01-06.jpg
        </image:loc>
        <image:caption>Le président guinéen Alpha Condé s’adresse aux médias après avoir voté dans un bureau de vote
            de Conakry, le 22 mars 2020.
        </image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/culture/article/2020/03/22/suzanne-clement-actrice-canadienne-le-quebec-a-une-forte-tradition-de-series-et-feuilletons_6034025_3246.html
    </loc>
    <lastmod>2020-03-22T15:37:49+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T15:37:49+01:00</news:publication_date>
        <news:title>Suzanne Clément, actrice canadienne : « Le Québec a une forte tradition de séries et feuilletons
            »
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/21/327/0/5568/2784/1440/720/60/0/0f70086_vXaG6yltE5iz4VrDF2qDMpN9.jpg
        </image:loc>
        <image:caption>L’actrice canadienne Suzanne Clément, lors de la 71e édition du Festival de Cannes, le 8 mai
            2018.
        </image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/sport/article/2020/03/22/coronavirus-le-sport-francais-cherche-comment-dire-qu-il-souhaite-un-report-des-jeux-olympiques_6034024_3242.html
    </loc>
    <lastmod>2020-03-22T17:29:21+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T15:33:22+01:00</news:publication_date>
        <news:title>Coronavirus : le sport français cherche comment exprimer son souhait d’un report des JO
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/19/337/0/3353/1676/1440/720/60/0/784f910_GGGTOK607_HEALTH-CORONAVIRUS-OLYMPICS_0319_11.JPG
        </image:loc>
        <image:caption>Plusieurs férédations sportives de poids, comme celles de natation et d’athlétisme aux
            Etats-Unis, ont fait comprendre, en fin de semaine, qu’elles sont favorables à un report des Jeux
            olympiques, prévus à Tokyo fin juillet.
        </image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/societe/article/2020/03/22/accueil-des-enfants-de-soignants-a-l-ecole-c-est-une-demarche-de-solidarite-naturelle_6034022_3224.html
    </loc>
    <lastmod>2020-03-22T16:56:53+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T14:41:08+01:00</news:publication_date>
        <news:title>Accueil des enfants de soignants à l’école : « C’est une démarche de solidarité naturelle »
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/22/0/0/4777/2385/1440/720/60/0/56cd31e_ARMSQexiyfWI90xGw-jwcXzD.jpg
        </image:loc>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/international/article/2020/03/22/au-mexique-l-etonnante-decontraction-du-president-amlo-face-au-coronavirus_6034020_3210.html
    </loc>
    <lastmod>2020-03-22T16:34:14+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T14:01:41+01:00</news:publication_date>
        <news:title>Au Mexique, l’étonnante décontraction du président « AMLO » face au coronavirus</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/22/760/0/4854/2427/1440/720/60/0/60b999d_gHeZ41lEmcUNmLcMt2nLBpxK.jpg
        </image:loc>
        <image:caption>Les espaces publics sont désinfectés pour éviter la propagation du nouveau coronavirus, à
            Guadalajara, au Mexique, le 20 mars.
        </image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/afrique/article/2020/03/22/coronavirus-l-epidemie-avance-en-afrique-subsaharienne-en-nombre-de-malades-et-de-pays-touches_6034018_3212.html
    </loc>
    <lastmod>2020-03-22T12:53:21+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T12:43:06+01:00</news:publication_date>
        <news:title>Coronavirus : l’épidémie avance en Afrique subsaharienne, en nombre de malades et de pays
            touchés
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/20/354/0/4512/2256/1440/720/60/0/ed44517_a34966929416464f9ed860d712a256cb-a34966929416464f9ed860d712a256cb-0.jpg
        </image:loc>
        <image:caption>Vendredi 20 mars, un marché de Lagos, au Nigeria (AP Photo/Sunday Alamba)</image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/politique/video/2020/03/22/suivez-en-direct-l-emission-questions-politiques-avec-jean-luc-melenchon_6034017_823448.html
    </loc>
    <lastmod>2020-03-22T12:24:15+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T12:22:12+01:00</news:publication_date>
        <news:title>Suivez en direct l’émission « Questions politiques » avec Jean-Luc Mélenchon</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>https://img.lemde.fr/2020/03/19/19/0/3125/1558/1440/720/60/0/c009a38_5412424-01-06.jpg
        </image:loc>
        <image:caption>Jean-Luc Melenchon, à l’Assemblée nationale, le 19 mars 2020.</image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/m-styles/article/2020/03/22/en-mode-confines-la-robe-de-chambre-en-soie_6034015_4497319.html
    </loc>
    <lastmod>2020-03-22T12:00:11+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T12:00:11+01:00</news:publication_date>
        <news:title>En mode confinés : la robe de chambre en soie</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>https://img.lemde.fr/2020/03/17/16/0/1165/581/1440/720/60/0/945e5b5_21105_3164207.jpg</image:loc>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/culture/article/2020/03/22/barbara-sans-fard-ni-artifice-sur-arte_6034014_3246.html
    </loc>
    <lastmod>2020-03-22T12:00:10+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T12:00:10+01:00</news:publication_date>
        <news:title>Barbara, sans fard ni artifice, sur Arte</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/19/15/0/1015/506/1440/720/60/0/1b14c97_n2Y7VWFo3GtyGRr8CX-HiVfm.jpg
        </image:loc>
        <image:caption>Image d’archives de Barbara.</image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/sante/video/2020/03/22/coronavirus-y-a-t-il-un-risque-prochain-de-penurie-alimentaire_6034013_1651302.html
    </loc>
    <lastmod>2020-03-22T13:39:27+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T11:42:59+01:00</news:publication_date>
        <news:title>Coronavirus : y a-t-il un risque prochain de pénurie alimentaire ?</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/19/651/0/6016/3004/1440/720/60/0/f8b624a_ws7aMabJUOF620MewwcleXfl.jpg
        </image:loc>
        <image:caption>Une employée remplit les rayons d'un intermarché à issy-Les-Moulineaux dans les Hauts de
            Seine avant l'ouverture du magasin, le 18 mars 2020. Le supermarché ouvre exceptionnellement de 8h à
            8h30 uniquement pour les clients de plus de 70 ans, pour répondre aux besoins en plein confinement
            provoqué par l'épidémie de Coronavirus. Lucas Barioulet pour Le Monde
        </image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/societe/article/2020/03/22/bordeaux-et-la-nouvelle-aquitaine-se-preparent-a-un-afflux-de-malades-dans-les-jours-a-venir_6034011_3224.html
    </loc>
    <lastmod>2020-03-22T12:43:08+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T11:18:25+01:00</news:publication_date>
        <news:title>Bordeaux et la Nouvelle-Aquitaine se préparent à un « afflux de malades dans les jours à venir
            »
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>https://img.lemde.fr/2020/03/21/691/0/4479/2234/1440/720/60/0/ea9540b_5422352-01-06.jpg
        </image:loc>
        <image:caption>A Bordeaux, le 21 mars.</image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/idees/article/2020/03/22/relocaliser-n-est-plus-une-option-mais-une-condition-de-survie-de-nos-systemes-economiques-et-sociaux_6034010_3232.html
    </loc>
    <lastmod>2020-03-22T11:00:10+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T11:00:10+01:00</news:publication_date>
        <news:title>« Relocaliser n’est plus une option mais une condition de survie de nos systèmes économiques et
            sociaux »
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2019/10/11/467/0/5604/2802/1440/720/60/0/3d0a809_xi_Egc7JVMq5WVCdS6uuN0xD.jpg
        </image:loc>
        <image:caption>« Dans l’industrie pharmaceutique () 80 % des principes actifs des médicaments sont importés
            de Chine et d’Inde, contre 20 % il y a trente ans ». Photo : Le port de Busan (Corée du Sud) avec des
            conteneurs.
        </image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/afrique/article/2020/03/22/hubert-velud-quand-je-raconte-a-mes-joueurs-soudanais-ce-qui-se-passe-en-france-ils-ne-me-croient-pas_6034008_3212.html
    </loc>
    <lastmod>2020-03-22T16:55:29+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T10:00:12+01:00</news:publication_date>
        <news:title>Hubert Velud : « Quand je raconte à mes joueurs soudanais ce qui se passe en France, ils ne me
            croient pas »
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/20/432/0/5184/2592/1440/720/60/0/5c6414a_cYb4lG5ubRKVAZ3WTX7s9gFY.jpg
        </image:loc>
        <image:caption>L’entraîneur français Hubert Velud avec les Crocodiles du Nil, l’quipe nationale du Soudan,
            le 18 février 2020 à Khartoum.
        </image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/international/article/2020/03/22/croatie-un-seisme-frappe-zagreb-et-fait-d-importants-degats-materiels_6034007_3210.html
    </loc>
    <lastmod>2020-03-22T09:13:31+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T09:13:31+01:00</news:publication_date>
        <news:title>Croatie : un séisme frappe Zagreb et fait d’importants dégâts matériels</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/22/301/0/3500/1750/1440/720/60/0/f6a5ffa_GDN_CROATIA-QUAKE-_0322_1L.JPG
        </image:loc>
        <image:caption>A Zagreb, dimanche 22 mars 2020.</image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/afrique/article/2020/03/22/face-au-coronavirus-les-puissantes-eglises-sud-africaines-tentent-de-s-adapter_6034006_3212.html
    </loc>
    <lastmod>2020-03-22T09:00:10+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T09:00:10+01:00</news:publication_date>
        <news:title>Face au coronavirus, les puissantes églises sud-africaines tentent de s’adapter</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/20/335/0/4000/1997/1440/720/60/0/1617a7d_iyMMTyyOX3k4YG6X6N-YP2tp.jpg
        </image:loc>
        <image:caption>Des fidèles de la Nala Mandate Church prient pour freiner la propagation du coronavirus, à
            Durban, en Afrique du Sud, le 19 mars 2020.
        </image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/idees/article/2020/03/22/coronavirus-cela-n-arrive-qu-aux-autres-aux-pauvres-aux-consommateurs-de-chauve-souris-et-autres-animaux-degoutants_6034005_3232.html
    </loc>
    <lastmod>2020-03-22T09:00:09+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T09:00:09+01:00</news:publication_date>
        <news:title>Coronavirus : « Cela n’arrive qu’aux autres, aux pauvres, aux consommateurs de chauve-souris et
            autres animaux dégoûtants »
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/17/466/0/3500/1750/1440/720/60/0/552ef32_FW1_HEALTH-CORONAVIRUS-VIETNAM-VISA_0317_11.JPG
        </image:loc>
        <image:caption>« Il n’y a pénurie ni de gel, ni de masques » (Touristes étrangers à Hanoï, le 17 mars).
        </image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/actualite-medias/article/2020/03/22/france-culture-se-mobilise-pour-aider-eleves-et-etudiants-confines_6034004_3236.html
    </loc>
    <lastmod>2020-03-22T13:19:23+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T08:59:57+01:00</news:publication_date>
        <news:title>France Culture se mobilise pour aider élèves et étudiants confinés</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>https://img.lemde.fr/2015/08/25/301/0/3496/1748/1440/720/60/0/ce6ea9d_15687-e7o6qo.jpg
        </image:loc>
        <image:caption>La Maison de la radio, ici en juin 2014.</image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/international/article/2020/03/22/vivre-l-epidemie-en-etant-expatrie-c-est-prendre-de-plein-fouet-la-distance_6034002_3210.html
    </loc>
    <lastmod>2020-03-22T08:09:07+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T08:09:07+01:00</news:publication_date>
        <news:title>« Vivre l’épidémie en étant expatrié, c’est prendre de plein fouet la distance »</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>https://img.lemde.fr/2020/03/20/416/0/4992/2496/1440/720/60/0/720a12d_5417617-01-06.jpg
        </image:loc>
        <image:caption>A Paris, le 20 mars.</image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/livres/article/2020/03/22/etre-ecrivain-en-inde-un-metier-a-risques_6034001_3260.html
    </loc>
    <lastmod>2020-03-22T08:00:16+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T08:00:16+01:00</news:publication_date>
        <news:title>Etre écrivain en Inde, un métier à risques</news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/18/398/0/4777/2388/1440/720/60/0/414c7d0_7WW6XOMF3lrYvmp6YYGhoM6R.jpg
        </image:loc>
        <image:caption>A Yavatmal, Maharashtra, en Inde. Sur l’affiche centrale, le portrait de Bhimrao Ramji
            ­Ambedkar (1891-1956), leader ­dalit dont les livres font toujours autorité et scandale en Inde
            aujourd’hui.
        </image:caption>
    </image:image>
</url>
<url>
    <loc>
        https://www.lemonde.fr/critique-litteraire/article/2020/03/22/romans-de-l-inde-bibhouti-bhoushan-banerji-manu-joseph-meena-kandasamy-jeet-thayil_6034000_5473203.html
    </loc>
    <lastmod>2020-03-22T08:00:15+01:00</lastmod>
    <news:news>
        <news:publication_date>2020-03-22T08:00:15+01:00</news:publication_date>
        <news:title>Romans de l’Inde : Bibhouti Bhoushan Banerji, Manu Joseph, Meena Kandasamy, Jeet Thayil…
        </news:title>
        <news:publication>
            <news:name>Le Monde</news:name>
            <news:language>fr</news:language>
        </news:publication>
    </news:news>
    <image:image>
        <image:loc>
            https://img.lemde.fr/2020/03/19/1603/0/1670/835/1440/720/60/0/6bf7fb2_tbnRrg7D2YL_LkrkhPG00Qsa.jpg
        </image:loc>
    </image:image>
</url>

При использовании simplexml_load_string я получаю PHP массив :

SimpleXMLElement Object
(
    [url] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [loc] => https://www.lemonde.fr/culture/article/2020/03/22/crise-sanitaire-malgre-les-annonces-du-gouvernement-les-intermittents-du-spectacle-restent-inquiets_6034031_3246.html
                    [lastmod] => 2020-03-12T20:00:12+01:00
                )

            [1] => SimpleXMLElement Object
                (
                    [loc] => https://www.lemonde.fr/climat/article/2020/03/22/l-eau-a-l-epreuve-des-changements-climatiques_6034029_1652612.html
                    [lastmod] => 2020-03-22T16:34:35+01:00<
                )

            [2] => SimpleXMLElement Object
                (
                    [loc] => https://www.lemonde.fr/journal-blouses-blanches/article/2020/03/22/journal-de-crise-des-blouses-blanches-la-consigne-est-de-se-cacher-quand-le-brancard-passe_6034028_6033712.html
                    [lastmod] => 2020-03-22T16:02:29+01:00
                )

Мне нужно получить указанный элемент c, так как я могу получить к ним доступ? Заранее спасибо!

РЕДАКТИРОВАТЬ:

Я нашел способ добраться до элементов пространства имен, но мой код работает в l oop, получая десятки тысяч элементов вместо примерно 200. Похоже, проблема с увеличением и URL (lo c). Я пытался отлаживать, но мне явно не хватает метода для начинающих. Вот мой код. Кто-нибудь может указать мне правильное направление, чтобы решить эту ошибку?

        $xmldataNews = simplexml_load_file('https://www.lemonde.fr/sitemap_news.xml');                     //  Load XML data
        $nameSpace = $xmldataNews->getNamespaces(true); // URI namespaces
        $nombreNews = $xmldataNews->count();
        $urls = $xmldataNews->url;
        for ($i = 0; $i < $nombreNews; $i++) {
            foreach ($urls as $url) {
                $news = ($url->children($nameSpace['news']))->news;   //  Get news name of the tag <news:name>
                $pubDateRaw = ($url->children($nameSpace['news']))->news->publication_date;  // Get the publication date of the news of the tag <news:publication_date>
                $datefr = date_create($pubDateRaw);  // date creation
                echo '<tr><td><a href="'.$url->loc.'" target="_blank">'.$news->title.'</td><td>'.date_format($datefr, "d/m/Y H:i:s").'</td></tr>';  // Display
            }
       }

Ответы [ 2 ]

1 голос
/ 22 марта 2020

Вы можете использовать XPath для перемещения по документу:

$xml = simplexml_load_string($content);
$xml->registerXPathNamespace('s', 'http://www.sitemaps.org/schemas/sitemap/0.9'); // xpath need to have an 'alias' to query the anonymous namespace

$urls = $xml->xpath('//s:url'); // retrieve all url items

foreach($urls as $url) // loop over each url item
{
    $url->registerXPathNamespace('s', 'http://www.sitemaps.org/schemas/sitemap/0.9');

    // string conversion gives you only the content of the node
    $title = (string) $url->xpath('news:news/news:title')[0];
    $loc = (string) $url->xpath('s:loc')[0];
    $lastmod = (string) $url->xpath('s:lastmod')[0];
    $pubDate = (string) $url->xpath('news:news/news:publication_date')[0] ;

    echo $title . PHP_EOL; 
    echo $loc . PHP_EOL ; 
    echo $lastmod . PHP_EOL ; 
    echo $pubDate . PHP_EOL; 
}

// означает, что вы просматриваете все узлы с этим именем, где бы в документе, и один / означает, что вы смотрите на прямые потомки узла. Вы можете прочитать документацию XPath, чтобы иметь больше команд.

XPath возвращает вам набор узлов, поэтому я всегда запрашиваю первый элемент с помощью [0] (при условии, что в вашем документе есть только один такой элемент)

0 голосов
/ 24 марта 2020

Мой старший преподаватель кода придумал это короткое и эффективное решение, предполагая, что любая сортировка перед выводом должна быть сделана, скажем, с js.

благодаря @ Joffrey-Schmitz для его подхода с Xpath (прокрутите немного вверх, чтобы увидеть его), который тоже работал хорошо.

Если кто-то знает, как реализовать сортировку выходных данных в PHP, я был бы очень заинтересован и благодарен!

    $xml = 'https://www.lemonde.fr/sitemap_news.xml';
    $xmldataNews = simplexml_load_file($xml);  // Load XML 
    $nameSpace = $xmldataNews->getNamespaces(true);          // namespace URI 
    $nombreNews = $xmldataNews->count();     // count elements in xml
    for ($i = 0; $i < $nombreNews; $i++) {  // increment conditions with elements count as limit
        foreach ($xmldataNews->url[$i]->children($nameSpace['news']) as $element)      // looping thru <url>/<news:news>/ elements, increment on <url>
            $datefr = new DateTime($element->publication_date);  // date representation (date format is donne inside echo
            echo '<tr><td><a href="'.$xmldataNews->url[$i]->loc.'" target="_blank">'.$element->title.'</td><td>'.date_format($datefr, "d/m/Y H:i:s").'</td></tr>';  // Display
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...