Loading file with simplexml_load_file

懵懂的女人 提交于 2019-12-12 13:05:20

问题


I am puzzled why this is not working yet i can echo the test.xml

<?php
$xml = simplexml_load_file('test.xml');

$movies = new SimpleXMLElement($xml);

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

回答1:


There is no need to do both, simplexml_load_file and create a new SimpleXML object.

simplexml_load_file already interprets an XML file into an object. (Keep in mind, it does not accept an XML string)

$movies = simplexml_load_file('test.xml');

Alternatively, you may directly load an XML string into a SimpleXML object.

$movies = new SimpleXMLElement(file_get_contents('test.xml'));

Either of the above approaches can be used to execute the following:

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



回答2:


When you go to load XML data, there's two ways to do it. You either load the contents of the XML file as a string, then pass that string to Simple XML:

$fileContents = file_get_contents('test.xml'); # reads the file and returns the string

$xml = simplexml_load_string($fileContents); # creates a Simple XML object from a string

print_r($xml); # output is a Simple XML object

...or, you load the file directly into a Simple XML Object:

$xml = simplexml_load_file('test.xml'); # Instantiates a new Simple XML object from the file, without you having to open and pass the string yourself

print_r($xml); # output is a Simple XML object

References: http://us2.php.net/manual/en/function.simplexml-load-file.php

http://us2.php.net/manual/en/function.simplexml-load-string.php



来源:https://stackoverflow.com/questions/9591695/loading-file-with-simplexml-load-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!