使用 simplexml 解析 xml 文件并访问属性 [英] Parsing a xml file using simplexml and accessing properties

查看:26
本文介绍了使用 simplexml 解析 xml 文件并访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析具有以下结构的 xml 文件:

I am trying to parse a xml file which has this structure:

<?xml version="1.0" encoding="UTF-8" ?> 
- <uclassify xmlns="http://api.uclassify.com/1/ResponseSchema" version="1.00">
  <status success="true" statusCode="2000" /> 
- <readCalls>
- <classify id="cls1">
- <classification>
  <class className="Arts" p="0.920034" /> 
  <class className="Business" p="2.81823e-005" /> 
  <class className="Computers" p="0.0040341" /> 
  <class className="Games" p="0.00846496" /> 
  <class className="Health" p="0.00203198" /> 
  <class className="Home" p="0.00136572" /> 
  <class className="Recreation" p="0.000526926" /> 
  <class className="Science" p="0.000160703" /> 
  <class className="Society" p="0.0611354" /> 
  <class className="Sports" p="0.00221835" /> 
  </classification>
  </classify>
  </readCalls>
  </uclassify>

我正在尝试访问类中的属性 className 和 p.这是我到目前为止的代码:

I am trying to access the properties className and p in class. This is the code that I have so far:

$resXml = simplexml_load_file($requestUrl); //$requestUrl is where the xml file is located
$children = $resXml->children('http://api.uclassify.com/1/ResponseSchema');

foreach ($children->readCalls->classify->classification->class as $d) {
    $currClassificationName = $d['className'];
    $currClassificationRating = (float) $d['p'];
    echo "$currClassificationName: $currClassificationRating" . "</br>";
}

这是输出:

: 0
: 0
: 0
: 0
: 0
: 0
: 0
: 0
: 0

我想得到的输出是:

Arts: 0.920034
Business: 2.81823e-005 
  ... 
Society: 0.0611354
Sports: 0.00221835

尝试了一段时间不同的东西,但无法解决这个问题.请帮忙.

Been trying different things for a while and cannot figure this out. Please Help.

推荐答案

试试这个:

$resXml = simplexml_load_file($requestUrl); //$requestUrl is where the xml file is located

foreach ($resXml->readCalls->classify->classification->class as $d) {
    $currClassificationName = $d['className'];
    $currClassificationRating = (float) $d['p'];
    echo "$currClassificationName: $currClassificationRating" . "</br>";
}

这篇关于使用 simplexml 解析 xml 文件并访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆