2013-10-10 43 views
0

我打算从xml文件中提取某些数据。我用simple_load_file()加载一个XML文件并获取对象元素,但我不知道如何访问它们。 XML文件就像下面:如何在使用`simple_load_file()`加载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. 
+0

自己调试'print_r($ xml)'。 [PHP手册也很棒](http://php.net/manual/en/function.simplexml-load-file.php) – Peter

+0

应该不太好用 – insanebits

+0

你可以试试$ xml-> Application ['version' ] – insanebits

回答

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

+1

基本上RTFM ... – Peter

+0

** Exacly .. ** =] – root

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 
} 
+0

您给了两个选择,哪一个更好? – ST3

+0

@ ST3为什么你认为有性能差异?除非这是一个巨大的差异,否则无关紧要。在这种情况下,确实没有任何东西,它只是用于做同样事情的替代语法。 – IMSoP

+0

我只是想惹恼我的室友,因为他想要非常聪明。 – ST3