1

i have been created an xml file and named it 'input.xml'. When i'm trying to add a file (attach to string) in php, i get 500 browser error.


This is how i importing my xml to variable (working way):

 $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;

This is how i want to import my xml (from input.xml file) (not working way):

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

This is how my php code looks like:

$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>";
}

And this is my input.xml file content:

<?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>
4
  • 1
    What error are you getting in your log? Commented Mar 16, 2019 at 17:42
  • 1
    try $movies = simplexml_load_file("input.xml"); as simplexml_load_file returns an SimpleXMLElement Object Commented Mar 16, 2019 at 17:47
  • Hello @gview, Im getting this error: Backend fatal error: PHP Fatal error: Uncaught Exception: String could not be parsed as XML in ..../zil/index.php:21\nStack trace:\n#0 ....}/zil/index.php(21): SimpleXMLElement->__construct('')\n#1 {main}\n thrown in ..../zil/index.php on line 21\n My 21 line: $movies = new SimpleXMLElement($xmlstr); Commented Mar 16, 2019 at 17:49
  • If you don't pass true as the third argument (data_is_url) in the constructor for new SimpleXMLElement(), it will use the first argument as XML-data, not as a path. So you must do: new SimpleXMLElement('input.xml', 0, true). You should always refer to the manual if you can't get a PHP function/object working as expected. Commented Mar 16, 2019 at 17:51

1 Answer 1

3

simplexml_load_file already returns a SimpleXMLElement for you. So, there's no need to use

$movies = new SimpleXMLElement($xmlstr);

Just:

$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>";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Feel free to accept an answer if it helps. Also if your other questions have a solution - accept ot/them too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.