基本的simpleXML工作示例? [英] Basic simpleXML working example?
问题描述
PHP中的simpleXML似乎有很多问题.我正在Windows上运行最新版本的php,但只是无法使simpleXML的基本示例如文档中所述正常工作.
It looks like there are many problems with simpleXML in PHP. I'm running the latest version of php on Windows and I just can not get the basic examples of simpleXML to work as in the documentation.
我的xml文件是:
<?xml version="1.0" encoding="ISO-8859-1"?>
<programme>
<title>Billy Bushwaka</title>
<episodeNumber>2</episodeNumber>
<description>Billy Bushwaka entertains</description>
<url>play.swf</url>
</programme>
我的PHP程序是:
<?php
$xml = simplexml_load_file("local.xml");
$result = $xml->xpath("//programme");
echo "Title: " . $result . "</br>";
?>
我所得到的是以下内容:
All I get is the following:
标题:数组
我如何获得标题:比利·布什瓦卡"?
How can I get "Title: Billy Bushwaka"?
没有重复的XML数据,所以我不想使用数组.
There are no repeats of XML data so I do not want to use arrays.
推荐答案
SimpleXML 101
-
首先,请始终在它们代表的节点后命名您的PHP变量.
First of all, always name your PHP variables after the node they represent.
// the root node is <programme/>
$programme = simplexml_load_file("local.xml");
访问子级(节点),就像它们是对象属性一样.
Access to children (nodes) as if they were object properties.
echo $programme->title;
如果有多个子代使用相同的名称,则可以指定其从0开始的位置
If there are multiple children using the same name, you can specify their 0-based position
// first <title/> child
echo $programme->title[0];
// create or change the value of the second <title/> child
$programme->title[1] = 'Second title';
像访问数组键一样访问属性
Access to attributes as if they were array keys
// <mynode attr="attribute value" />
echo $mynode['attr'];
XPath始终返回一个数组.
XPath always returns an array.
回到您的情况,访问该<title />
节点的最佳方法将是
Back to your case, the best way to access that <title />
node would be
$programme = simplexml_load_file("local.xml");
echo "Title: " . $programme->title;
这篇关于基本的simpleXML工作示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!