Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

simple XML problem

Status
Not open for further replies.

snowboardr

Programmer
Feb 22, 2002
1,401
PH
I am unable to get the following script to display anything and i have modified it multiple times to try and get it to work before posting this:

index.php
Code:
<?php
if (file_exists('myfile.xml')) {
    $xml = simplexml_load_file('myfile.xml');
 
   //print_r($xml);
  echo $xml->item->description;
} else {
    exit('Failed to open test.xml.');
}
?>

myfile.xml
[/code]
<?xml version="1.0"?>

<item>
<description>Hello!</description>
</item>

[/code]


however this works fine:
Code:
<?php
include 'example.php';

$xml = new SimpleXMLElement($xmlstr);

echo $xml->movie[0]->plot; // "So this language. It's like..."
?>

example.php
Code:
<?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;
?>

Jason

[red]Army[/red] : [white]Combat Engineer[/white] : [blue]21B[/blue]

 
you need a root element according to the manual.

Code:
<?xml version="1.0"?>
<root>
   <item>
      <description>Hello!</description>
   </item>
</root>

the code will then ignore the root element. in your example the value would have been in $xml->description
 
[1] The parallelism goes like this.
>echo $xml->item->description;
[tt]echo $xml->description;[/tt]
The $xml is pointing to the root node, but for some curious design philosophy/legacy(?), the name of the root node is not "naturally" exposed.

[2] Using the same constructor may help to see the parallelism more clearly. It is this.
>$xml = simplexml_load_file('myfile.xml'); [blue]//it is fine[/blue]
[tt]$xml = new SimpleXMLElement('myfile.xml',null,true);[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top