Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

php - Basic simpleXML working example?

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.

My xml file is:

<?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> 

My PHP program is:

<?php
$xml = simplexml_load_file("local.xml");

$result = $xml->xpath("//programme");
echo "Title: " . $result . "</br>";
?>

All I get is the following:

Title: Array

How can I get "Title: Billy Bushwaka"?

There are no repeats of XML data so I do not want to use arrays.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SimpleXML 101

  1. First of all, always name your PHP variables after the node they represent.

    // the root node is <programme/>
    $programme = simplexml_load_file("local.xml");
    
  2. Access to children (nodes) as if they were object properties.

    echo $programme->title;
    
  3. 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';
    
  4. Access to attributes as if they were array keys

    // <mynode attr="attribute value" />
    echo $mynode['attr'];
    
  5. XPath always returns an array.


Back to your case, the best way to access that <title /> node would be

$programme = simplexml_load_file("local.xml");
echo "Title: " . $programme->title;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...