douyuanqia665858 2014-09-13 20:14
浏览 49

PHP - 无法将字符串解析为XML [重复]

This question already has an answer here:

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.

</div>
  • 写回答

2条回答 默认 最新

  • dongzhi9906 2014-09-13 20:19
    关注

    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)

    评论

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测