I am using a simplexml to parse xml in a block. Then I realized that if the xml string is not valid that will break things so I have added a try-catch statement. Testing how it works I put an invalid xml address and that gave the error message that I created and didn't break the site like before. But, I get lots of warning messages. Is that normal?

Here is a snippet of the php code

$source = 'xmlurl';
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
try {
     $xml = new SimpleXMLElement($data);
     print $xml->date;
     print '<br>';
     print $xml->city;
     print '<br>';
     print '<br>';
} catch (Exception $e) {
      print 'Invalid xml string';
}
?>

Here is what the report - log shows

SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: ^ in drupal/includes/common.inc(1685) : eval()'d code on line 11.

Any suggestions on how to do this properly.

Thanks

Comments

maozet’s picture

$parsed_xml = simplexml_load_string($data);

3elwa’s picture

I get the same thing when I tried $parsed_xml = simplexml_load_string($data);. The only difference is that it doesn't throw an exception with invalid xml source. But the warnings I get are all the same.

I am new to php and drupal so I am not sure what is the best practice in doing that xml parse. In addition to trying to solve the problem that I am having I would also appreciate any advise or comments on the entire approach to doing the parsing.

Thanks

ardr’s picture

you've missed a semicolon off the end of the first line.
$source = 'xmlurl'

Try putting one in.

3elwa’s picture

Sorry this is a mistake only in the post. I fixed it now.

Let me clarify also what the issue is. The code that I have in the post works exactly like intended (with the xmlurl being the actual url of the xml). But, what got me started on the whole post is that at some point I put in the wrong xml and when I saved the block, I got a white screen. Luckily I was able to back to the previous window and fix the problem. I am not sure how I would have fixed the problem if I was not able to navigate back to the previous window through the browser.

Because of this I wanted to write the code properly to avoid any problems that may break the site. Hence, the going down the try-catch path. Which worked great and my site doesn't break If there is a problem with the xml url. The only issue is that there are lots of warnings that get generated and I was wondering if there is a better way to deal with that problem.