PHP - 无法将String解析为XML

时间:2014-09-13 20:14:40

标签: php xml simplexml

我目前正在使用以下代码,但未返回任何结果:

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

    echo $title;    
?>

XML代码:

<?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>

如果有人知道如何解决这个问题,我很想知道。感谢。

2 个答案:

答案 0 :(得分:5)

第4和第5行中的XML似乎无效:

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

应该是:

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

我建议在http://www.w3schools.com/xml/xml_validator.asp使用XML验证程序来调试XML代码的错误。

此外,由于您的根元素是item,您可能想要更改PHP代码:

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

(我手边没有PHP副本来测试这个,但根据http://php.net/manual/en/simplexml.examples-basic.php,这应该可行)

答案 1 :(得分:0)

Xml只能有1个根元素,在您的示例中,根是item

加载到SimpleXML时,您可以使用$xml->getName()

获取根名称
$url = 'http://myknowledge.org.uk/xml';
$item = new SimpleXMLElement($url, null, true);
$title = $item->title;
$description = $item->description;

或者,如果您需要多个

,则应将项目包含在另一个根目录中items