Parsing a xml file using simplexml and accessing properties

↘锁芯ラ 提交于 2019-12-09 03:23:42

问题


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>

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>";
}

This is the output:

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

The output I am trying to get is:

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.


回答1:


Try this out:

$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>";
}


来源:https://stackoverflow.com/questions/4577302/parsing-a-xml-file-using-simplexml-and-accessing-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!