无法从simplexml_load_string获取节点

问题描述 投票:0回答:1

我知道这个问题已被提出,但我发现的所有解决方案都没有对我有用。

鉴于这种:

SimpleXMLElement Object
(
    [0] => 
    <test>
        <blah>
          <x>
          filler
          </x>
        </blah>
    </test>

)

我如何获得<x>值?

我试过了

$doc = simplexml_load_string($xml_response);
print_r($doc->test->blah->x);
print_r($doc[0]->test->blah->x);
print_r($doc->{'0'}->test->blah->x);
print_r((string)$doc->{'0'}->test->blah->x);
print_r((string)$doc[0]->test->blah->x);
print_r((string)$doc->test->blah->x);

这是原始的xml:

1.0" encoding="UTF-8" ?>
<xxx>
    &lt;test&gt;
        &lt;blah&gt;
            &lt;x&gt;fillertexthere&lt;/x&gt;
        &lt;/blah&gt;
        &lt;fillertexthere&lt;/Reason&gt;
    &lt;/test&gt;
</xxx>%  
php xml simplexml-load-string
1个回答
0
投票

你的SimpleXMLElement包含一个字符串。我认为这是因为你的xml包含&lt;&gt;

你能做的是首先使用htmlspecialchars_decode,然后加载你的字符串。

(我从你的原始xml中删除了这行&lt;fillertexthere&lt;/Reason&gt;%

$xml_response = <<<DATA
<?xml version="1.0" encoding="UTF-8" ?>
    <xxx>
        &lt;test&gt;
            &lt;blah&gt;
                &lt;x&gt;fillertexthere&lt;/x&gt;
            &lt;/blah&gt;
        &lt;/test&gt;
    </xxx>
DATA;
$xml_response = htmlspecialchars_decode($xml_response);

var_dump($xml_response);

这看起来像:

object(SimpleXMLElement)#1 (1) {
  ["test"]=>
  object(SimpleXMLElement)#2 (1) {
    ["blah"]=>
    object(SimpleXMLElement)#3 (1) {
      ["x"]=>
      string(14) "fillertexthere"
    }
  }
}

您可以像这样回显x的值:

echo $doc->test->blah->x;
© www.soinside.com 2019 - 2024. All rights reserved.