SimpleXML kullanırken nasıl nesne adını alabilirim?

2 Cevap php

: Format c Her yineleme aracılığıyla foreach gereken bir nesne dizidir şu ise,

$a->b->c

Ve ben:

$z = $a->b
foreach($z as $key => $value)
echo $value['field'];

$ Anahtar Ben geçerli değerlere sahip olsa bile, boş olarak gelir. Nasıl nesnenin adı alabilirim?

2 Cevap

XML ve SimpleXML ile yüklemek için aşağıdaki kod parçasını göz önüne alındığında:

$str = <<<XML
<root>
    <a>
        <b>
            <c>glop</c>
            <d>test</d>
        </b>
    </a>
</root>
XML;
$xml = simplexml_load_string($str);

Bunu üzerinde yineleme edebilmek için, $xml->a->b bir dizi "cast" olabilir:

foreach ((array)$xml->a->b as $name => $value) {
    echo "$name : $value<br />";
}

Ve çıktı bu tür alırsınız:

c : glop
d : test

(maybe not exactly the same XML string as yours, but I hope this will help you get to the solution -- if it does, can you edit your question to show us you XML data, and the output you'll willing to get ? )

De, kılavuz sayfasını alıntı Converting to array section:

If an object is converted to an array, the result is an array whose elements are the object's properties.
The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name.

XML:

<a>
  <b>
    <c />
    <d />
    <e />
  </b>
</a>

PHP-Kodu:

$xml = new SimpleXMLElement($file_url, true);
foreach($xml->b->children() as $node) {
    echo $node->getName() . "\n";
}

Size vermek istiyorum:

c
d
b

PHP's manual daha fazla referans için bkz.