skip to Main Content

Hi I have an xml file like that

<param typ="bool" nazwa="balkon">true</param>

<param typ="bool" nazwa="lazienka_wc">true</param>

<param typ="int" nazwa="liczbapieter">5</param>

<param typ="int" nazwa="liczbapokoi">3</param>

<param typ="int" nazwa="liczbalazienek">1</param>

I am looping through this like that:

            foreach($oferta->param as $p){
                print_r($p->attributes()->nazwa);
            }

I print out nazwa attr for every param but how can i get values: true, true, 5, 3, 1?

2

Answers


  1. Try this:

    $xml = <<<XML
       <root>
           <param typ="bool" nazwa="balkon">true</param>
           <param typ="bool" nazwa="lazienka_wc">true</param>
           <param typ="int" nazwa="liczbapieter">5</param>
           <param typ="int" nazwa="liczbapokoi">3</param>
           <param typ="int" nazwa="liczbalazienek">1</param>
        </root>
    XML;
    $oferta = new SimpleXMLElement($xml);
    $values = [];
    foreach($oferta->param as $p){
        $values[] = $p;
    }
    error_log('values: '.implode(', ',$values));
    

    Which outputs in my error log file:

    values: true, true, 5, 3, 1
    
    Login or Signup to reply.
  2. To get the string content of a SimpleXMLElement, you cast it to a string:

    $example = simplexml_load_string('<foo>Hello</foo>');
    $content = (string)$example;
    var_dump($content); // string(5) "Hello"
    

    So in your case, you want to cast $p to string in the loop:

    foreach($oferta->param as $p){
        $value = (string)$p;
    }
    

    Also, there is a short-hand for $p->attributes()->nazwa, which is $p['nazwa']. With either syntax, that also returns an object, so you probably want to cast that to a string as well:

    foreach($oferta->param as $p){
        $value = (string)$p;
        $nazwa = (string)$p['nazwa'];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search