简体   繁体   中英

SOLVED :Why am I having “Fatal error: Uncaught Exception: String could not be parsed as XML”?

I am trying to get data from my API to the main page but it keeps giving me this error:

Warning: file_get_contents(http://localhost/PaimentElec/server/apiDetails.php?xml=<movie><id>2</id></movie> ): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\xampp\htdocs\PaimentElec\client\rep.php on line 19
**Fatal error**: Uncaught Exception: String could not be parsed as XML in C:\xampp\htdocs\PaimentElec\client\rep.php:20 Stack trace: #0 C:\xampp\htdocs\PaimentElec\client\rep.php(20): SimpleXMLElement->__construct('') #1 {main} thrown in C:\xampp\htdocs\PaimentElec\client\rep.php on line 20 

At first I thought maybe I have errors in my API XML, so I used https://www.w3schools.com/xml/xml_validator.asp to double check and it said that my code is fine. When I open the link for the API (eg http://localhost/PaimentElec/server/apiDetails.php?xml=<movie><id>2</id></movie> ) it shows the data perfectly.

This is the API:

<?xml version="1.0"  encoding="UTF-8"?>
<movies>
<?php
$db = new PDO("mysql:host=localhost;dbname=homecinema","root","");
    $xml=$_GET["xml"];
    $retour= new SimpleXMLElement($xml);
    $id=$retour->id;
    $retour=$db->query("select * from movie where id='$id' ");
    $movies=$retour->fetchAll(); 
    foreach($movies as $movie){
    ?>
      <movie>
      <title> <?php echo $movie ["title"];?></title>
      </movie>
<?php   
}?>
</movies>

and this is where I called the API (page name rep.php):

$id=$_POST["id"];    //this is the line 19
$xmlrq="<movie><id>$id</id></movie>";
$xml=file_get_contents("http://localhost/PaimentElec/server/apiDetails.php?xml=$xmlrq");
$retour= new SimpleXMLElement($xml);

PS: the id was sent by another page:

<form method="POST" action="rep.php">
    <input type="hidden" name="id" value="<?php echo $movie->id; ?>">
</form>

The string which you receive is not valid xml. here you can check for correct standard of XML https://www.w3schools.com/xml/schema_intro.asp , but I suggest you to forget for xml (if it's possible) because XML is old and not best solution, for web you can use JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM