开发者

Trying to read XML nodes using PHP DOM

I'm trying to read the relevant nodes in the following XML string, to finally display:

flerror:0

Message from directory:Pings being forwarded to 11 services!

<?xml v开发者_Python百科ersion="1.0"?>
<methodResponse>
  <params>
    <param>
      <value>
        <struct>
  <member><name>flerror</name><value><boolean>0</boolean></value></member>
  <member><name>message</name><value><string>Pings being forwarded to 11 services!</string></value></member>
</struct>
      </value>
    </param>
  </params>
</methodResponse>

I tried using:

$doc = new DOMDocument();
$doc->loadXML($xmlString);
$value = $doc->getElementsByTagName("value");
$value = $value->item(0)->nodeValue;

and obtained:

<br>flerror0<br>
  messagePings being forwarded to 11 services!

I can then use string parsing functions to separate out the strings, but that I need a cleaner solution.

Any suggested improvements that will possibly avoid the additional string parsing?

Thanks!


I have not much experience with DOMDocument. But looks like your xml is small and simple, I would suggest to use simple xml. Here is what I have wrote

<?php
$xmlString = "<?xml version=\"1.0\"?>
<methodResponse>
  <params>
    <param>
      <value>
        <struct>
  <member><name>flerror</name><value><boolean>0</boolean></value></member>
  <member><name>message</name><value><string>Pings being forwarded to 11 services!</string></value></member>
</struct>
      </value>
    </param>
  </params>
</methodResponse>
";

$xml = simplexml_load_string($xmlString);
echo '<pre>';
print_r($xml->params->param->value);
echo '</pre>';

?>

And got

SimpleXMLElement Object
(
    [struct] => SimpleXMLElement Object
        (
            [member] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [name] => flerror
                            [value] => SimpleXMLElement Object
                                (
                                    [boolean] => 0
                                )

                        )

                    [1] => SimpleXMLElement Object
                        (
                            [name] => message
                            [value] => SimpleXMLElement Object
                                (
                                    [string] => Pings being forwarded to 11 services!
                                )

                        )

                )

        )

)

I think now it will be much easier to access every node.


I had a similar issue with DOMDocument, and it seems that it's not able to give content from a node named "param"...

Try changing the name to "parameter", it will work

True story

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜