PHP - 无法将字符串解析为 XML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25827262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - String could not be parsed as XML
提问by user3287037
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 代码:
<?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.
如果有人知道如何解决这个问题,我很想知道。谢谢。
回答by Peter
The XML appears to be invalid in lines 4 and 5:
XML 在第 4 行和第 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.aspto debug errors with your XML code.
我建议使用http://www.w3schools.com/xml/xml_validator.asp上的 XML 验证器来调试 XML 代码的错误。
Also, as your root element is item, you may want to change your PHP code:
此外,由于您的根元素是 item,您可能需要更改您的 PHP 代码:
<?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)
(我手头没有 PHP 的副本来测试这个,但根据http://php.net/manual/en/simplexml.examples-basic.php,这应该有效)
回答by Imre L
Xml can have only 1 root element, in your example the root is item
Xml 只能有 1 个根元素,在您的示例中,根是 item
When loading to SimpleXML you can get the root name with $xml->getName()
加载到 SimpleXML 时,您可以获得根名称 $xml->getName()
$url = 'http://myknowledge.org.uk/xml';
$item = new SimpleXMLElement($url, null, true);
$title = $item->title;
$description = $item->description;
Or you should enclose you items in another root i.e items
if you need multiple
或者您应该将您的项目包含在另一个根目录中,即items
如果您需要多个