Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - String could not be parsed as XML [duplicate]

Tags:

php

xml

simplexml

I am currently using the following code, but no result is returned:

<?php   
    $url = 'http://myknowledge.org.uk/xml';
    $xml = new SimpleXMLElement(file_get_contents($url));
    foreach ($xml->item as $item) {
        $title = $item->title;
    }

    echo $title;    
?>

The XML Code:

<?xml version="1.0" encoding="utf-8"?>
<item>
    <title>Apple</title>
    <notableFor>Fruit</notableFor>
    <wikiid>Apple</wikiid>
    <description>The apple is the pomaceous fruit of the apple tree, Malus domestica of the rose family. It is one of the most widely cultivated tree fruits, and the most widely known of the many members of genus Malus that are used by humans.</description>
    <img></img>
    <website></website>
    <translate>
        <de>Äpfel</de>
        <fr>pomme</fr>
        <it>mela</it>
        <es>manzana</es>
        <ru>яблоко</ru>
    </translate>
    <nutritionalInfomation name="Apple" quantity="100g">
        <calories>52</calories>
        <carb>14</carb>
        <fibre>2.4</fibre>
        <protein>0.3</protein>
        <fat>0.2</fat>
    </nutritionalInfomation>
</item>

If anybody has an idea how to fix this I would love to know. Thanks.

like image 916
user3287037 Avatar asked Apr 24 '26 18:04

user3287037


1 Answers

The XML appears to be invalid in lines 4 and 5:

<notableFor>Fruit</title>
<wikiid>Apple</title>

Which should be:

<notableFor>Fruit</notableFor>
<wikiid>Apple</wikiid>

I recommend using the XML validator at http://www.w3schools.com/xml/xml_validator.asp to debug errors with your XML code.

Also, as your root element is item, you may want to change your PHP code:

<?php   
    $url = 'http://myknowledge.org.uk/xml';
    $item = new SimpleXMLElement(file_get_contents($url));
    $title = $item->title;
    $description = $item->description;
?>

(I don't have a copy of PHP on hand to test this, but according to http://php.net/manual/en/simplexml.examples-basic.php, this should work)

like image 171
Peter Avatar answered Apr 27 '26 07:04

Peter