如何使用命名空间解析 XML?

2024-03-23

这是我的 xml 文件,我试图使用 PHP simplexml_load_string() 函数类解析它,但它只打印</description>标签和 xml 的其余部分不会返回

XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dfpvideo="http://api.google.com/dfpvideo" xmlns:media="http://search.yahoo.com/mrss/" xmlns:ngc="http://xml.natgeotv.com/fields" xmlns:ngs="http://prod.ngs.org/ngs" xmlns:ngsDebug="http://prod.ngs.org/ngs-debug" xmlns:ngsTax="http://prod.ngs.org/taxonomy" xmlns:os="http://a9.com/-/spec/opensearch/1.1/" xmlns:pl="http://xml.theplatform.com/data/object" xmlns:pl1="http://access.auth.theplatform.com/data/Account/2388557369" xmlns:pl2="http://access.auth.theplatform.com/data/Account/2423130747" xmlns:pla="http://xml.theplatform.com/data/object/admin" xmlns:plfile="http://xml.theplatform.com/media/data/MediaFile" xmlns:pllist="http://xml.theplatform.com/data/list" xmlns:plmedia="http://xml.theplatform.com/media/data/Media" xmlns:plrelease="http://xml.theplatform.com/media/data/Release" xmlns:wpf="http://prod.ngs.org/wpf" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ytcp="http://www.youtube.com/schemas/cms/2.0" version="2.0">
   <channel>
      <title>NG Video</title>
      <link>http://feed.theplatform.com/f/ngs/dCCn2isYZ9N9</link>
      <description>NG Video</description>
      <os:startIndex>1</os:startIndex>
      <os:itemsPerPage>100</os:itemsPerPage>
      <pllist:entryCount>1</pllist:entryCount>
      <item>
         <pl:id>http://data.media.theplatform.com/media/data/Media/97681476000</pl:id>
         <guid isPermaLink="false">a4ad87f6-cbe4-4816-9580-b6679af0ea73</guid>
         <title>NG Live!: Sheikh of the Arctic</title>
         <description>&lt;p&gt;Having completed more solo trips to the Poles than anyone else on the planet, Børge Ousland is sometimes surprised by who he runs into crossing the vast Arctic tundra.&lt;/p&gt;</description>
         <author />
         <media:keywords />
         <media:restriction relationship="deny" type="country" />
         <media:content channels="2" samplingrate="44.1" bitrate="535.928" medium="video" duration="175.031" expression="full" fileSize="11725511" framerate="29.97" type="video/mp4" height="346" isDefault="true" url="http://link.theplatform.com/s/ngs/ekLOLGt3bemU?feed=NG%20Video" width="616">
            <media:hash algo="md5">0AF4AD25977BF50888075D3547F67173</media:hash>
            <pl:added>Sun, 22 Dec 2013 02:41:46 GMT</pl:added>
            <plfile:assetType>mpeg4</plfile:assetType>
         </media:content>
         <media:thumbnail expression="full" fileSize="79478" type="image/jpeg" height="556" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_990x556_177596483623.jpg" width="990">
            <media:hash algo="md5">60FFCE1C849440050CBCBD259EF2CE65</media:hash>
            <pl:added>Sun, 02 Mar 2014 05:26:41 GMT</pl:added>
            <plfile:assetType>Poster</plfile:assetType>
            <plfile:assetType>MED</plfile:assetType>
         </media:thumbnail>
         <media:thumbnail expression="full" fileSize="209762" type="image/jpeg" height="720" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720.jpg" width="1280">
            <media:hash algo="md5">08AC83096DC5F7E48A7CDE4BFA23A27A</media:hash>
            <pl:added>Sun, 02 Mar 2014 05:26:30 GMT</pl:added>
            <plfile:assetType>Mezzanine Image</plfile:assetType>
         </media:thumbnail>
         <media:thumbnail expression="full" fileSize="2962" type="image/jpeg" height="68" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_120x68_177597507564.jpg" width="120">
            <media:hash algo="md5">605D86F9A2B606D97A653576E6CE99D2</media:hash>
            <pl:added>Sun, 02 Mar 2014 05:26:45 GMT</pl:added>
            <plfile:assetType>Thumbnail</plfile:assetType>
         </media:thumbnail>
         <media:thumbnail expression="full" fileSize="23707" type="image/jpeg" height="270" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_480x270_177598019578.jpg" width="480">
            <media:hash algo="md5">73F78D0314E0CC15CDA5C36AAE4560AD</media:hash>
            <pl:added>Sun, 02 Mar 2014 05:26:42 GMT</pl:added>
            <plfile:assetType>Poster</plfile:assetType>
            <plfile:assetType>X-SM</plfile:assetType>
         </media:thumbnail>
         <media:thumbnail expression="full" fileSize="83905" type="image/jpeg" height="576" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_1024x576_177598019579.jpg" width="1024">
            <media:hash algo="md5">5C4B05CE487697A63F4FEC8B51009497</media:hash>
            <pl:added>Sun, 02 Mar 2014 05:26:43 GMT</pl:added>
            <plfile:assetType>Poster</plfile:assetType>
            <plfile:assetType>LG</plfile:assetType>
         </media:thumbnail>
         <media:thumbnail expression="full" fileSize="114846" type="image/jpeg" height="720" isDefault="false" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_1280x720_177598019580.jpg" width="1280">
            <media:hash algo="md5">31BFBD1020B2277B7E6FDD353973F263</media:hash>
            <pl:added>Sun, 02 Mar 2014 05:26:43 GMT</pl:added>
            <plfile:assetType>Poster</plfile:assetType>
            <plfile:assetType>X-LG</plfile:assetType>
         </media:thumbnail>
         <media:thumbnail expression="full" fileSize="37132" type="image/jpeg" height="360" isDefault="true" url="http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_640x360_177598019582.jpg" width="640">
            <media:hash algo="md5">2654AFBE193785E29FF0533CF977A473</media:hash>
            <pl:added>Sun, 02 Mar 2014 05:26:44 GMT</pl:added>
            <plfile:assetType>Poster</plfile:assetType>
            <plfile:assetType>SM</plfile:assetType>
         </media:thumbnail>
         <pubDate>Sat, 21 Dec 2013 06:56:49 GMT</pubDate>
         <plmedia:defaultThumbnailUrl>http://pmdvod.nationalgeographic.com/NG_Video/997/323/67322_1_1280x720_640x360_177598019582.jpg</plmedia:defaultThumbnailUrl>
         <plmedia:provider />
         <pl1:youTubeInStreamStandard>true</pl1:youTubeInStreamStandard>
         <pl1:youTubeInStreamTrueView>true</pl1:youTubeInStreamTrueView>
         <pl1:youTubeInVideo>true</pl1:youTubeInVideo>
         <pl1:youTubePublic>false</pl1:youTubePublic>
         <ngs:clipTypeOld>none</ngs:clipTypeOld>
         <ngs:contentCreationDate>Mon, 13 May 2013 19:03:22 GMT</ngs:contentCreationDate>
         <ngs:network>NGS</ngs:network>
         <ngs:redirectToExternal>never</ngs:redirectToExternal>
         <ngs:requiresAuth>false</ngs:requiresAuth>
         <ngs:series>{"updated_datetime":null,"creation_datetime":null,"is_active":false,"name":"National Geographic Live","translated_names":[],"synonyms":[],"uuid":null,"notes":null,"objectType":"org.ngs.video.Show","groups":[],"url":null}</ngs:series>
         <ngs:seriesName>National Geographic Live</ngs:seriesName>
         <ngsTax:location>{"updated_datetime":"2014-04-03T19:09:42.570Z","is_active":true,"creation_datetime":"2013-11-28T20:27:32.077Z","parent":"http://taxonomy.nationalgeographic.com/api/v1/locations/eea9ad49-32fc-3a7c-bf15-cfeabdaa2fb7","geonames_uri":null,"url":"http://taxonomy.nationalgeographic.com/api/v1/locations/ff4e742f-46e6-3867-be8c-003a7af8f86c","dbpedia_uri":"http://dbpedia.org/page/Arctic","name":"Arctic","longitude":0.0,"hierarchy":"earth/arctic/","latitude":0.0,"uuid":"ff4e742f-46e6-3867-be8c-003a7af8f86c","notes":"","objectType":"org.ngs.taxonomy.GeoLocation","groups":["Place","region"],"english_name":null,"parentName":"Earth"}</ngsTax:location>
         <ngsTax:location>{"updated_datetime":"2014-05-28T20:43:43.719Z","is_active":true,"creation_datetime":"2013-11-28T20:01:26.936Z","synonyms":[null,null],"parent":"http://taxonomy.nationalgeographic.com/api/v1/locations/eea9ad49-32fc-3a7c-bf15-cfeabdaa2fb7","geonames_uri":"http://sws.geonames.org/6697173/","url":"http://taxonomy.nationalgeographic.com/api/v1/locations/d2ce52aa-c6ac-3a13-9f8c-59cb13ecb924","dbpedia_uri":null,"name":"Antarctica","translated_names":[null],"longitude":16.40626,"hierarchy":"earth/antarctica/","latitude":-78.15856,"uuid":"d2ce52aa-c6ac-3a13-9f8c-59cb13ecb924","notes":"","objectType":"org.ngs.taxonomy.GeoLocation","groups":["Place","continent"],"english_name":null,"parentName":"Earth"}</ngsTax:location>
         <ngsTax:organization>{"updated_datetime":"2014-05-02T15:37:25.776Z","creation_datetime":"2013-11-28T19:40:52.694Z","is_active":true,"name":"National Geographic Live","synonyms":[null],"uuid":"bae34d69-0601-342b-abe4-345c4c2486c4","notes":"","objectType":"org.ngs.taxonomy.Organization","english_name":null,"groups":["Organization"],"url":"http://taxonomy.nationalgeographic.com/api/v1/organizations/bae34d69-0601-342b-abe4-345c4c2486c4"}</ngsTax:organization>
         <ngsTax:slug>ousland-sheikh-bonus-nglive</ngsTax:slug>
         <ngsTax:subject>{"updated_datetime":"2014-06-04T15:56:21.047Z","definition":"","is_active":true,"creation_datetime":"2013-11-28T19:59:40.956Z","scope_note":"","synonyms":[null],"parent":"http://taxonomy.nationalgeographic.com/api/v1/subjects/83bf00d5-93bd-3cca-acc3-543652f06d52","url":"http://taxonomy.nationalgeographic.com/api/v1/subjects/58f9272e-f37b-3550-a228-a5ee119553ae","name":"Explorers","hierarchy":"exploration/explorers/","uuid":"58f9272e-f37b-3550-a228-a5ee119553ae","notes":"","objectType":"org.ngs.taxonomy.Subject","groups":["Subject"],"english_name":null,"parentName":"Exploration"}</ngsTax:subject>
         <ngsTax:subject>{"updated_datetime":"2014-01-29T14:56:08.338Z","definition":"","is_active":true,"creation_datetime":"2013-11-28T19:52:45.402Z","scope_note":"","parent":"http://taxonomy.nationalgeographic.com/api/v1/subjects/83bf00d5-93bd-3cca-acc3-543652f06d52","url":"http://taxonomy.nationalgeographic.com/api/v1/subjects/83c5f238-8dbc-373e-9d62-4deb4c59e122","name":"Expeditions","hierarchy":"exploration/expeditions/","uuid":"83c5f238-8dbc-373e-9d62-4deb4c59e122","notes":"","objectType":"org.ngs.taxonomy.Subject","groups":["Subject"],"english_name":null,"parentName":"Exploration"}</ngsTax:subject>
         <ngsTax:subject>{"updated_datetime":"2014-02-10T19:47:37.384Z","definition":"","is_active":true,"creation_datetime":"2014-01-16T17:48:21.375Z","scope_note":"","synonyms":[null,null,null],"parent":"http://taxonomy.nationalgeographic.com/api/v1/subjects/a817863e-de0f-3ffd-944d-c75ed20308ff","url":"http://taxonomy.nationalgeographic.com/api/v1/subjects/f0c33fd8-5e31-36b2-9229-b71628df3367","name":"Travel","hierarchy":"travel-and-adventure/travel/","uuid":"f0c33fd8-5e31-36b2-9229-b71628df3367","notes":"","objectType":"org.ngs.taxonomy.Subject","groups":["Subject"],"english_name":null,"parentName":"Travel and Adventure"}</ngsTax:subject>
         <ngsTax:title>NG Live!: Sheikh of the Arctic</ngsTax:title>
         <wpf:allTaxonomyId>18160</wpf:allTaxonomyId>
         <wpf:allTaxonomyId>1589</wpf:allTaxonomyId>
         <wpf:allTaxonomyId>858</wpf:allTaxonomyId>
         <wpf:altLinkedLegacyUrl />
         <wpf:author />
         <wpf:firstPublishedTime>Mon, 13 May 2013 19:11:17 GMT</wpf:firstPublishedTime>
         <wpf:id>13615</wpf:id>
         <wpf:lastPublishedTime>Mon, 03 Feb 2014 21:50:20 GMT</wpf:lastPublishedTime>
         <wpf:lineupName>Nat Geo Live 2</wpf:lineupName>
         <wpf:locationMigration>Arctic</wpf:locationMigration>
         <wpf:locationMigration>Antarctica</wpf:locationMigration>
         <wpf:metaKeyword>Nat Geo Live</wpf:metaKeyword>
         <wpf:metaKeyword>Nat Geo Live!</wpf:metaKeyword>
         <wpf:metaKeyword>lecture</wpf:metaKeyword>
         <wpf:metaKeyword>National Geographic Live</wpf:metaKeyword>
         <wpf:metaKeyword>National Geographic Live!</wpf:metaKeyword>
         <wpf:metaKeyword>NGLive</wpf:metaKeyword>
         <wpf:metaKeyword>NG Live</wpf:metaKeyword>
         <wpf:metaKeyword>Nat Geo Events</wpf:metaKeyword>
         <wpf:metaKeyword>Børge Ousland</wpf:metaKeyword>
         <wpf:metaKeyword>polar</wpf:metaKeyword>
         <wpf:metaKeyword>adventure</wpf:metaKeyword>
         <wpf:metaKeyword>explore</wpf:metaKeyword>
         <wpf:metaKeyword>exploration</wpf:metaKeyword>
         <wpf:metaKeyword>expedition</wpf:metaKeyword>
         <wpf:metaKeyword>ski</wpf:metaKeyword>
         <wpf:metaKeyword>North Pole</wpf:metaKeyword>
         <wpf:metaKeyword>loneliness</wpf:metaKeyword>
         <wpf:metaKeyword>strange</wpf:metaKeyword>
         <wpf:metaKeyword>visitor</wpf:metaKeyword>
         <wpf:metaKeyword>ice</wpf:metaKeyword>
         <wpf:metaKeyword>photo</wpf:metaKeyword>
         <wpf:metaKeywords>Nat Geo Live, Nat Geo Live!, lecture, National Geographic Live, National Geographic Live!, NGLive, NG Live, Nat Geo Events, Børge Ousland, polar, adventure, explore, exploration, expedition, ski, North Pole, loneliness, strange, visitor, ice, photo</wpf:metaKeywords>
         <wpf:organizationMigration>National Geographic Live</wpf:organizationMigration>
         <wpf:sitePath>Specials Video::Nat Geo Live::Nat Geo Live 2</wpf:sitePath>
         <wpf:siteUrlPath>/video/specials/nat-geo-live-specials/nat-geo-live-2/ousland-sheikh-bonus-nglive/</wpf:siteUrlPath>
         <wpf:subjectMigration>Explorers</wpf:subjectMigration>
         <wpf:subjectMigration>Expeditions</wpf:subjectMigration>
         <wpf:subjectMigration>Travel</wpf:subjectMigration>
         <wpf:taxonomyId>18160</wpf:taxonomyId>
         <ytcp:youTubeAssetType>web</ytcp:youTubeAssetType>
         <ytcp:youTubeSavedMatchRights>Monetize in all countries</ytcp:youTubeSavedMatchRights>
         <ytcp:youTubeSavedUsageRights>Monetize in all countries</ytcp:youTubeSavedUsageRights>
      </item>
   </channel>
</rss>

这是我的代码

   function parsexml($xml)
   {
   $xmlparse=simplexml_load_string($xml)
   var_dump($xmlparse);
   }

您不会获得所有节点,因为它们使用命名空间,例如:pl:id。要解析这些,您可以使用 Xpath。第一个例子抓住了所有pl:added第二个得到media:hash.

仅当您知道文件将始终使用相同的前缀时,才可以使用以下内容。如果没有,您必须为您使用的每个 simpleXMLElement 对象注册名称空间。

<?    
$str = '*your string here*';    
$xml = simplexml_load_string($str);

// to get pl:added 
foreach($xml->xpath('//media:content') as $element) {
    $added = $element->xpath('//pl:added');
}
//output $added
echo "<pre>";
var_dump($added);

// to get media:hash
foreach($xml->xpath('//media:thumbnail') as $element) {
    $hash = $element->xpath('//media:hash');
}
//output $hash
echo "<pre>";
var_dump($hash);
?>

当您需要注册名称空间时,可以执行以下操作。首先,您可以 var dump 命名空间,以便知道需要使用哪个 url。

["os"]=>string(36) "http://a9.com/-/spec/opensearch/1.1/"因此,对于操作系统,您需要该网址。

<?    
$str = '*your string here*';    
$xml = simplexml_load_string($str);

// to get the namespaces uncomment the next 3 lines
// $namespaces = $xml->getNamespaces(true);
// echo "<pre>";
// var_dump($namespaces);

$xml->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');

foreach($xml->xpath('//media:content') as $element) {
    $element->registerXPathNamespace('pl', 'http://xml.theplatform.com/data/object');
    $added = $element->xpath('//pl:added');
}

echo "<pre>";
var_dump($added);

$xml->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');

foreach($xml->xpath('//media:thumbnail') as $element) {
    $element->registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');
    $hash = $element->xpath('//media:hash');
}

echo "<pre>";
var_dump($hash);
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用命名空间解析 XML? 的相关文章

  • 无法使用 android.support.v7.widget.AppCompatTextView 实例化以下类

    最近我在 android studio 的应用程序中将我的 sdk 从 25 更改为 26 我在所有 xml 中都遇到了这个奇怪的错误 目前 该错误并没有以我能看到的任何方式影响我的应用程序 但每次我必须编辑或更改 xml 中的某些内容时
  • PMA 4.5.2.0 file_exists():open_basedir 限制生效

    从 PPA 在我的 Ubuntu 服务器上安装 phpMyAdmin 后 https launchpad net nijel archive ubuntu phpmyadmin https launchpad net nijel archi
  • PHP mail() 函数不发送邮件

    我有一个小问题 我正在使用一个工作脚本 在我的测试帐户 共享服务器上工作 使用 mail 函数通过 PHP 发送邮件 我刚刚得到了一个专用服务器 但我还无法让该功能发挥作用 在过去的 10 个小时左右的时间里 我阅读了有关 BIND 用于
  • Ubuntu 18.04升级后php7.2-curl无法安装

    今天从 16 04 升级到 18 04do release upgrade d 在升级过程中 我被告知一些软件包将被删除 其中包括 删除 libperl5 22 lxc common perl modules 5 22 php imagic
  • PHP 如果不存在,则从字符串中删除 ','

    我正在运行这段代码 stmt pdo conn gt prepare SELECT from admin where support emails support emails and logged logged and disabled
  • Facebook 中用户的时区是如何编码的

    我需要检查用户的时区 但我找不到它的真正定义 参考API http developers facebook com docs reference api user says 用户的时区与 UTC 的偏移量 现在在维基百科上这些是可能的时区
  • 如何计算加权平均值?

    我的语言是PHP 但是算法应该是相当通用的 我有一个关联数组 比方说 评级和评级次数 ratings array 1 gt 1 2 gt 3 3 gt 6 4 gt 3 5 gt 3 这相当于 1 2 2 2 3 3 3 3 3 3 4 4
  • PHP 的 PDO 可以限制为单个查询吗?

    PHP 的 PDO 允许通过 query 方法或作为准备好的语句同时执行多个查询 以下两个示例均有效 Two SQL queries query SELECT FROM table DROP table Execute via query
  • PHP 相等变量

    我想知道是否有任何方法可以检查大量变量是否相等 如果我只有几个变量 我可以这样做 if a b a c b c 但是 如果我有 20 个变量 则需要一些时间来编写所有组合 还有其他方法吗 if count array unique arra
  • 如何从另一个xml文件动态更新xml文件?

    我想从另一个 xml 文件更新 xml 文件 我使用了一个 xml 文件 如下所示 one xml
  • 有没有好的方法来解析用户代理字符串?

    我有一个Java接收模块User Agent来自最终用户浏览器的字符串的行为需要略有不同 具体取决于浏览器类型 浏览器版本甚至操作系统 例如 FireFox 7 0 Win7 Safari 3 2 iOS9 我明白了User Agent由于
  • 如何将 XMP XML 块序列化为现有的 JPEG 图像?

    我有许多 JPEG 图像 其中包含损坏的 XMP XML 块 我可以轻松修复这些块 但我不确定如何将 固定 数据写回图像文件 我目前正在使用 JAVA 但我愿意接受任何能让这项任务变得容易的事情 这是目标关于 XMP XML 的另一个问题
  • Yii 查询时对相关模型的限制

    我遇到了极限问题 我正在使用的代码如下 model PostCategory model record model gt with array posts gt array order gt posts createTime DESC li
  • laravel 5.4 在请求验证之前修改数据[关闭]

    Closed 这个问题是无法重现或由拼写错误引起 help closed questions 目前不接受答案 我有我的自定义请求 它扩展了 Backpack CrudController 现在我想重写 ValidatesWhenResolv
  • 隐藏产品价格和添加到购物车按钮,但不隐藏 WooCommerce 中未注册用户的变体

    在我的 WooCommerce 商店中 我想隐藏价格 直到客户登录为止 我有以下代码可以实现这一点 add action init hide price function hide price if is user logged in re
  • 如何使用 PHP 从 MySQL 检索特定值?

    好吧 我已经厌倦了 过去一周我花了大部分空闲时间试图解决这个问题 我知道 SQL 中的查询已更改 但我无法弄清楚 我能找到的所有其他帖子似乎都已经过时了 如果有人能帮助我 我将非常感激 我想做的就是使用手动输入数据库的唯一 密码 来检索行的
  • 图像创建从jpeg() PHP

    我正在使用 imagecreatefromjpeg 函数合并两张图片 现在我面临的问题是 当我使用服务器中的图片时 它工作正常 而当我使用其他网站的图片时 它不起作用 例如 当我使用这个 PHP 文件时http coolfbapps in
  • PHP 文件服务脚本:下载不可靠?

    这篇文章最初是关于 ServerFault 的一个问题 https serverfault com questions 131156 user receiving partial downloads https serverfault co
  • 使用 powershell 编辑 XML

    好吧 我感觉自己像个大白痴 为了工作中的管理目的 我使用 Powershell 已经有一段时间了 也就是说 编写脚本不是我的强项 现在 我正在尝试编写一个 PS 脚本 将一个部分添加到一堆机器上的 XML 中 以添加设置来解决我们在某个应用
  • 禁用/启用用户访问/下载,但允许 php 编辑 - 使用 chown 和 chmod

    我想 move uploaded files到某个文件夹 比方说http localhost myproject protected 并且 PHP 应该能够rm mv cp 里面的一切protected 例如 启用 禁用用户对任何文件的访问

随机推荐