如何将xml文件附加到php变量

时间:2019-03-16 17:39:11

标签: php xml

我已经创建了一个xml文件,并将其命名为“ input.xml”。当我尝试在php中添加文件(附加到字符串)时,出现500个浏览器错误。


这是我将xml导入变量的方式(工作方式):

 $xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>Movie 1</title>
 </movie>

  <movie>
  <title>Movie 2</title>
 </movie>

 <categories>
  <category>
    <name>Example category</name>
  </category>
 </categories>
</movies>
XML;

这是我想从xml(从input.xml文件)导入xml的方式(不起作用):

 $xmlstr = simplexml_load_file("input.xml");

这是我的php代码的样子:

$movies = new SimpleXMLElement($xmlstr);

foreach ($movies->movie as $mov) {
   echo "We found a movie!<br>";
}

foreach ($movies->categories as $cat) {
    echo "We found a category!<br>";
}

这是我的input.xml文件内容:

<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>Movie 1</title>
 </movie>

  <movie>
  <title>Movie 2</title>
 </movie>

 <categories>
  <category>
    <name>Example category</name>
  </category>
 </categories>
</movies>

1 个答案:

答案 0 :(得分:2)

simplexml_load_file已经为您返回了SimpleXMLElement。因此,无需使用

$movies = new SimpleXMLElement($xmlstr);

就:

$movies = simplexml_load_file("input.xml");

foreach ($movies->movie as $mov) {
   echo "We found a movie!<br>";
}

foreach ($movies->categories as $cat) {
    echo "We found a category!<br>";
}