PHP - 字符串无法被解析为XML

3

我目前正在使用以下代码,但没有返回结果:

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

如果有人有修复这个问题的想法,我很愿意知道。谢谢。


那是一个公正的观点。不是答案...抱歉。 - user3287037
XML代码中有一个错误,我已经纠正了,但似乎没有任何改变。 - user3287037
只是一点提示: “Äpfel” 是“Apfel”的复数。 - Gumbo
我将努力进行更正。谢谢。 - user3287037
请参考PHP手册,了解如何跟踪、报告和/或显示错误。此外,请参阅PHP手册,了解如何处理异常。这里有一个参考问题:https://dev59.com/aHRA5IYBdhLWcg3wvQlh - 另一个我关闭了你的问题,具体链接为https://dev59.com/hOo6XIcBkEYKwwoYPR_f#12772851 - hakre
显示剩余2条评论
2个回答

7
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的说法,这应该可以工作。


我刚刚修正了这个问题,但是 echo "$title" 仍然没有返回值。 - user3287037
我已经用更新的PHP代码编辑了我的答案。 - Peter

0

XML 只能有一个根元素,在你的例子中,根元素是 item

当加载到 SimpleXML 时,您可以使用 $xml->getName() 获取根名称

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

或者你应该将你的项目封装在另一个根目录中,例如items,如果你需要多个。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接