PHP - 无法将String解析为XML

use*_*037 2 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;    
?>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*ter 5

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

<notableFor>Fruit</title>
<wikiid>Apple</title>
Run Code Online (Sandbox Code Playgroud)

应该是:

<notableFor>Fruit</notableFor>
<wikiid>Apple</wikiid>
Run Code Online (Sandbox Code Playgroud)

我建议使用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;
?>
Run Code Online (Sandbox Code Playgroud)

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