-3

I would like to get specific value from XML data in Cake Php. This is what I've got so far:

after doing print_r($output) in controller this is what I've got;

<?xml version="1.0" encoding="UTF-8"?>
<response>
  <xmlArray>
    <numbers>52619657</numbers>
  </xmlArray>
</response>

Because I don't know how to get it directly from xml, so I convert it to array in controller as cakePHP doc mention.

$xmlArray = Xml::toArray(Xml::build($out));

The result from print_r($xmlArray); is

Array
(
    [response] => Array
        (
            [xmlArray] => Array
                (
                    [numbers] => 52619657
                )
        )
)

I tried to get the numbers '52619657'. So my attempt is

print_r ($xmlArray['numbers']);

But it doesn't work (error is Undefined index:). So I try to use IN method like here, but actually I don't know how to do it. How do I get the number '52619657'? in cake PHP.

Thank you so much

akpackage
  • 17
  • 4
  • 1
    since is a nested array you have to do `$xmlArray['response']['xmlArray']['numbers']` – arilia Oct 19 '17 at 09:44
  • 1
    You are linking to the CakePHP 1.3 docs, but you're obviously not using CakePHP 1.3, as no such method exists there. Also the linked question regarding `IN` refers to the query builder, which is something completely different. – ndm Oct 19 '17 at 09:57

1 Answers1

2

I don't see why you would need a 3rd party library, like Cake's XML class for this. You can do this easily with SimpleXML:

$response = simplexml_load_string($output);
echo $response->xmlArray->numbers;

Your approach doesn't work because your $xmlArray is a nested array and doing $xmlArray['numbers'] will try to fetch numbers from the first level. You would need to use $xmlArray['response']['xmlArray']['numbers']; Knowing how to read an array is basic knowledge, so consider rereading this part in the PHP manual.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • 2
    btw, CakePHPs [**`Xml::build()`**](https://api.cakephp.org/2.10/class-Xml.html#_build) returns a `SimpleXMLElement` object by default, it is merely a convenience wrapper that abstracts handling various types of input (string, array, URL), and stuff like disabling loading external entities. – ndm Oct 19 '17 at 10:04