如何使用PHP解析CDATA XML?

时间:2017-02-23 13:55:39

标签: php xml

我正在开发一个用PHP编写的Web服务。我想使用IEEE Explore API显示数据 - 它是一个REST API。它输出XML,如下所示。

我想使用foreach循环解析此数据。我试图检索数据。但问题是所有标记值都在 CDATA 包装内。

我该如何解决这个问题?

<?xml version="1.0" encoding="UTF-8"?>
<document>
    <rank>1</rank>
    <title><![CDATA[Gait Rhythm Fluctuation Analysis for Neurodegenerative Diseases by Empirical Mode Decomposition]]></title>
    <authors><![CDATA[Peng Ren;  Shanjiang Tang;  Fang Fang;  Lizhu Luo;  Lei Xu;  Maria L. Bringas-Vega;  Dezhong Yao;  Keith M. Kendrick;  Pedro A. Valdes-Sosa]]></authors>
    <controlledterms>
        <term><![CDATA[diseases]]></term>
        <term><![CDATA[feature extraction]]></term>
        <term><![CDATA[gait analysis]]></term>
    </controlledterms>
    <pubtitle><![CDATA[IEEE Transactions on Biomedical Engineering]]></pubtitle>
    <punumber><![CDATA[10]]></punumber>
    <pubtype><![CDATA[Journals &amp; Magazines]]></pubtype>
    <publisher><![CDATA[IEEE]]></publisher>
    <abstract><![CDATA[Previous studies have indicated that gait rhythm of gait rhythms.]]></abstract>
    <issn><![CDATA[0018-9294]]></issn>
    <arnumber><![CDATA[7422732]]></arnumber>
    <doi><![CDATA[10.1109/TBME.2016.2536438]]></doi>
    <publicationId><![CDATA[7422732]]></publicationId>
    <partnum><![CDATA[7422732]]></partnum>
</document>

2 个答案:

答案 0 :(得分:-1)

请检查代码:

<?php
//require_once 'connection.php';
function xmlToArray($xml,$ns=null){
 $a = array();
 for($xml->rewind(); $xml->valid(); $xml->next()) {
  $key = $xml->key();
  if(!isset($a[$key])) { $a[$key] = array(); $i=0; }
  else $i = count($a[$key]);
  $simple = true;
  foreach($xml->current()->attributes() as $k=>$v) {
   $a[$key][$i][$k]=(string)$v;
   $simple = false;
  }
  if($ns) foreach($ns as $nid=>$name) {
   foreach($xml->current()->attributes($name) as $k=>$v) {
    $a[$key][$i][$nid.':'.$k]=(string)$v;
    $simple = false;
   }
  }
  if($xml->hasChildren()) {
   if($simple) $a[$key][$i] = xmlToArray($xml->current(), $ns);
   else $a[$key][$i]['content'] = xmlToArray($xml->current(), $ns);
  } else {
   if($simple) $a[$key][$i] = strval($xml->current());
   else $a[$key][$i]['content'] = strval($xml->current());
  }
  $i++;
 }
 return $a;
}

$xml = new SimpleXmlIterator('test.xml', null, true);
$namespaces = $xml->getNamespaces(true);
// echo '<pre>'; print_r($namespaces); die;
$arr = xmlToArray($xml,$namespaces);
echo '<pre>'; print_r($arr); die;
?>

我能够获得CDATA中的字段值。将您的XML数据放在test.xml文件中。

答案 1 :(得分:-1)

我在阅读php.net文档时找到了解决问题的另一个简单的解决方案。我只是传递我的网址$xml = simplexml_load_file($mainurl, 'SimpleXMLElement',LIBXML_NOCDATA);。我得到了完整的数据。