【问题标题】:simplexml_load_string has a bug?simplexml_load_string 有错误?
【发布时间】:2014-02-09 14:49:26
【问题描述】:

当我使用 simplexml_load_string 时,我发现一个问题,使用后丢失数据。

$xml = '<dblp>
<inproceedings key="conf/aaim/He07" mdate="2007-06-28">
<author>Dan He</author>
<title>
<i>BMA</i>
<sup>*</sup>
: An Efficient Algorithm for the One-to-Some Shortest Path Problem on Road Maps.
</title>
<pages>346-357</pages>
<year>2007</year>
<crossref>conf/aaim/2007</crossref>
<booktitle>AAIM</booktitle>
<ee>http://dx.doi.org/10.1007/978-3-540-72870-2_33</ee>
<url>db/conf/aaim/aaim2007.html#He07</url>
</inproceedings>
</dblp>';
print_r(simplexml_load_string($xml));

运行结果:

  SimpleXMLElement Object
(
    [inproceedings] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [key] => conf/aaim/He07
                    [mdate] => 2007-06-28
                )

            [author] => Dan He
            [title] => SimpleXMLElement Object
                (
                    [i] => BMA
                    [sup] => *
                )

            [pages] => 346-357
            [year] => 2007
            [crossref] => conf/aaim/2007
            [booktitle] => AAIM
            [ee] => http://dx.doi.org/10.1007/978-3-540-72870-2_33
            [url] => db/conf/aaim/aaim2007.html#He07
        )

)

数据“:路线图上一对一最短路径问题的有效算法”在哪里?
我希望 xml 到 array.but 数据丢失?谢谢。 我想要结果:

Array
(
[0] => Array
(
    [inproceedings] =>Array
    (
        [author] => Dan He
        [title] => Array
        (
            [0] => BMA
            [2] => *
            [5] => : An Efficient Algorithm for the One-to-Some Shortest Path Problem on Road Maps.
        )

        [pages] => 346-357
        [year] => 2007
        [crossref] => conf/aaim/2007
        [booktitle] => AAIM
        [ee] => http://dx.doi.org/10.1007/978-3-540-72870-2_33
        [url] => db/conf/aaim/aaim2007.html#He07
    )

)

)

【问题讨论】:

  • 我希望它在 SimpleXMLElement 对象title 中。另见stackoverflow.com/questions/5132231/…
  • 不要print_r SIMPLEXML 类,或者至少不要根据其输出得出任何结论。它们为您提供了某种表示形式,可以帮助您稍微识别事物,但在很多情况下它在表面之下是模糊的。
  • 用“有错误?”来表达问题。大多数情况下,这不是 Stackoverflow 的有效问题,而是 PHP bugtracker 中的搜索请求(此规则有例外,但此问题不属于其中)。另见github.com/IMSoP/simplexml_debug

标签: php xml


【解决方案1】:

SimpleXMLElement 的第一条规则是:你不要print_r()var_dump() SimpleXMLElement 对象

至于为什么看不到信息,请看documentation的这个注释:

注意: SimpleXML 制定了一个规则,为大多数方法添加迭代属性。无法使用 var_dump() 或其他任何可以检查对象的方法查看它们。

要访问标题,您可以:

$xmlObj = simplexml_load_string($xml);
$title = (string) $xmlObj->inproceedings->title;

SimpleXMLElement 对象的属性是对象本身,因此您需要通过在开头添加(string)(或使用strval())将它们转换为字符串。现在它们的值将被转换为字符串而不是对象。

要检查 SimpleXML 对象时应该使用什么?

您可以使用IMSoPsimplexml_dump()simplexml_tree() 辅助函数。这是project on GitHub

【讨论】:

  • 添加到 Amal 的答案中,可以选择 echo $xml-&gt;asXML();,如果在 HTML 文档中,可能是 echo htmlspecialchars($xml-&gt;asXML());
猜你喜欢
  • 2015-08-30
  • 2013-02-14
  • 2011-02-23
  • 1970-01-01
  • 2020-02-19
  • 2019-02-25
  • 2017-10-03
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多