PHP SimpleXML - 获取值

时间:2018-03-22 22:31:18

标签: php mysql simplexml

我正在尝试使用SimpleXML和PHP从存储在数据库中的XML中获取值。我的XML的一部分看起来像这样:

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.8.0_161" class="java.beans.XMLDecoder">
  <object class="atavism.agis.objects.AgisMob" id="AgisMob0">
  <void property="name">
    <string>Rachels</string>
  </void>
  <void property="oid">
  <object class="atavism.server.engine.OID" id="OID0">
  <void property="data">
    <long>41321</long>
  </void>

我在同一个“文档”中也有其他XML,如下所示:

所以说,我可能需要在属性属性等于“name”的地方获取它。我也计划稍后从这份文件中获取其他信息,只需要弄清楚如何。

这是我到目前为止的代码:

$blob_query = mysqli_query($dbh8, "SELECT * FROM objstore WHERE obj_id='$characterId' AND type='PLAYER' AND namespace_int='3' ORDER BY obj_id DESC LIMIT 1");           
        if($blob_query){
            $blob_row = mysqli_fetch_assoc($blob_query);
            $data = $blob_row['data'];

            $xml=simplexml_load_string($data) or die("Error: Cannot create object");
            echo $xml->void[0]->string;

        }

它没有显示任何内容。它应该显示“Rachels”。非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

You're missing the <object> tag to get <string> tag content.

Assuming you XML look likes (as a valid XML):

$data = '<?xml version="1.0" encoding="UTF-8"?>
<java version="1.8.0_161" class="java.beans.XMLDecoder">
  <object class="atavism.agis.objects.AgisMob" id="AgisMob0">
      <void property="name">
        <string>Rachels</string>
      </void>
  </object>
  <void property="oid">
      <object class="atavism.server.engine.OID" id="OID0">
          <void property="data">
            <long>41321</long>
          </void>
      </object>
  </void>
</java>';

You have to use:

$xml=simplexml_load_string($data) or die("Error: Cannot create object");
echo $xml->object->void[0]->string;

outputs:

Rachels

Note also that [0] is not necessary (in this case):

echo $xml->object->void->string;

答案 1 :(得分:0)

尝试插入容器中的所有元素,如

<?php 
$xmld = '
<obj>
<void property="data">
  <long>41321</long>
</void>
<void property="datad">
   <long>413213</long>
</void></obj>';
 $xml=simplexml_load_string($xmld) or die("Error: Cannot create object");

echo $xml->void[0]->long;