【问题标题】:Parsing very simple XML with PHP用 PHP 解析非常简单的 XML
【发布时间】:2018-11-08 20:03:08
【问题描述】:

非常简单的请求(我认为)我没有成功。

这里是xml文件的内容:

<?xml version="1.0" encoding="utf-8"?>
<status USER_ID="xxxxx">OK</status>

当前php:

$xml=simplexml_load_file($file) or die("Error: Cannot create object");
print_r($xml);

输出:

SimpleXMLElement Object ( [@attributes] => Array ( [USER_ID] => xxxxx ) [0] => OK ) 

现在我被卡住了

如何在我的 php 脚本中获取 USER_ID 的值以及状态为“OK”的状态。

谢谢。

【问题讨论】:

  • (string) $xml-&gt;attributes()-&gt;USER_ID 应该可以工作
  • $user_id=(@DOMDocument::loadHTML($xml))-&gt;getElementsByTagName("status")-&gt;item(0)-&gt;getAttribute("USER_ID"); $text=(@DOMDocument::loadHTML($xml))-&gt;getElementsByTagName("status")-&gt;item(0)-&gt;textContent; var_dump($user_id,$text);

标签: php xml


【解决方案1】:

在下面试试这个

echo "Display the user id: " . $xml['USER_ID'];
echo "Display the status: " . $xml[0];

希望这会对您有所帮助。

【讨论】:

    【解决方案2】:

    如果你不喜欢 SimpleXml(和我一样),你也可以使用 XMLReader 类:

    $XMLReader = new XMLReader;
    $XMLReader->XML(file_get_contents($file)); //you can use $XMLReader->open('file://'.$file); too
    //move to first node
    $XMLReader->read();
    //get an attribute
    echo "USER_ID:".$XMLReader->getAttribute('USER_ID')."\n";
    //get the contents of the tag as a string
    echo "Status:" .$XMLReader->readString();
    

    输出:

    USER_ID:xxxxx
    Status:OK
    

    Sandbox

    【讨论】:

      猜你喜欢
      • 2012-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 2013-02-28
      • 2017-12-07
      相关资源
      最近更新 更多