0

我打算从 xml 文件中获取一些特定的数据。我曾经simple_load_file()加载一个xml文件并获取对象元素,但我不知道如何访问它们。xml 文件如下所示:

<?mxl version="1.0">
<metaData>
<Application version="1.0" type="32">
   <options>
       <section name="A">
           <description>...</description>
           ...
       <section name="B">
       ....
   </options>
</Application>
</metaData>

我的代码:

$xml = simplexml_load_file($url);
echo $xml->Application->version; // get the version but failed
echo $xml->Application->options->section...//I want to get the data from each section, but I don't know how to visit the elements.
4

2 回答 2

3

尝试这个

// attribute accessing
$version = (string)$xml->Application['version']
// or
$version = (string)$xml->Application->attributes()->version;


// acess children
foreach($xml->Application->section as $section)
{
    // you can work with single section here
}

// or other way
foreach($xml->Application->children() as $section)
{
    // you can work with single section here
}
于 2013-10-10T20:43:45.143 回答
0

在我回答这个问题之前,让我告诉你一个小提示,每当你有任何问题尝试在谷歌上搜索它,就像在这种情况下,我会搜索:

PHP simplexml examples

好的,假设我们有一个 XML 内容:

<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
XML;
?>

我们可以这样解析 XML 数据:

<?php


$movies = new SimpleXMLElement($xmlstr);

echo $movies->movie[0]->plot;
?>

更多示例请访问: http: //php.net/manual/en/simplexml.examples-basic.php

对于这个特定的问题,您应该使用SimpleXMLElement::children

于 2013-10-10T20:39:56.467 回答