doujingdai5521 2018-03-22 19:02
浏览 35
已采纳

PHP SimpleXMLElement xpath

I am trying to perform a simple xpath lookup using an XML file from an HTTP POST. I've been pulling my hair out, as this should work!! Everything I've found thus far is a result of the namespace, but I have no namespace in this XML.

<?xml version="1.0" encoding="UTF-8"?>
<foo>
 <bar>
  <name>Frank</name>
 </bar>
</foo>

Here is the simple code I'm using.

$xml = new SimpleXMLElement(file_get_contents("php://input");
print_r($xml->xpath("//FOO/bar/name"));

This gives me an empty array!

Array
(
  [0] => SimpleXMLElement Object
      (
      )
)

If I just do print_r($xml->xpath("//foo")); I see it has the data, but as soon as I try to get the value of name, I get nothing. :(

Array
(
  [0] => SimpleXMLElement Object
      (
      [bar] => SimpleXMLElement Object
         (
              [name] => Frank
         )
      )
)

What is the deal?? Thank you!!

  • 写回答

1条回答 默认 最新

  • dsyq40772 2018-03-22 19:39
    关注

    This gives me an empty array!

    No it doesn't. Look closely at your output, and you will see that you have an array with one result in it, which is a SimpleXMLElement object.

    Unfortunately, print_r doesn't handle SimpleXMLElement objects very well, and in some versions of PHP works better than others, so it doesn't accurately show you what SimpleXMLElement you have.

    But your production code won't be relying on print_r, it will be relying on the actual content of that element, so let's see if we can get the content:

    // Text content of an element is (string)$element
    var_dump( (string)$first_result ); # string(5) "Frank"
    // Render element back to XML
    var_dump( $first_result->asXML() ); # string(18) "<name>Frank</name>"
    

    This gives the right output in all versions of PHP on 3v4l.org. So there isn't actually a problem at all! :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧