Home > Software engineering >  For loop for outputting array in PHP cURL
For loop for outputting array in PHP cURL

Time:10-22

I have XML like

<user>
 <researcher>
  <researcher_keywords>
    <researcher_keyword>
        <value>Value A</value>
    </researcher_keyword>
    <researcher_keyword>
        <value>Value B</value>
    </researcher_keyword>
    <researcher_keyword>
        <value>Value C</value>
    </researcher_keyword>
   </researcher_keywords>
 </researcher>
</user>

...and I want to be able to output all the <researcher_keyword> values using a foreach loop or similar separated by a pipe character |

I can access specific values using code like: $oXML->researcher->researcher_keywords->researcher_keyword[0]->value ?? null;

...but how do I output whats in the array using a loop?

I thought something like this would work but no luck:

 $oXML2 = new SimpleXMLElement( $response2 );
...
 foreach($oXML2->researcher_keyword as $researcher_keyword){
    echo (string)$researcher_keyword['value'];
 }

and var_dump($oXML2->researcher->researcher_keywords); outputs:

object(SimpleXMLElement)#19 (1) { ["researcher_keyword"]=> array(7) { [0]=> object(SimpleXMLElement)#18 (1) { ["value"]=> string(19) "Ancient Mesopotamia" } [1]=> object(SimpleXMLElement)#20 (1) { ["value"]=> string(30) "Ancient Near Eastern religions" } [2]=> object(SimpleXMLElement)#16 (1) { ["value"]=> string(12) "Hebrew Bible" } [3]=> object(SimpleXMLElement)#21 (1) { ["value"]=> string(21) "American religion" } [4]=> object(SimpleXMLElement)#22 (1) { ["value"]=> string(18) "American magic" } [5]=> object(SimpleXMLElement)#23 (1) { ["value"]=> string(23) "American literature" } [6]=> object(SimpleXMLElement)#24 (1) { ["value"]=> string(20) "American thought" } } } 

I could use the below code assuming there'll never be more than 10 keywords but it's not ideal.

  $j = 10;
  for($i = 0; $i < $j ; $i  ) {
    $keyword_r = $oXML2->researcher->researcher_keywords->researcher_keyword[$i]->value ?? null;
      echo $keyword_r . "<br>";
  }

Thanks

CodePudding user response:

Use this code:

$s = '<user>
 <researcher>
  <researcher_keywords>
    <researcher_keyword>
        <value>Value A</value>
    </researcher_keyword>
    <researcher_keyword>
        <value>Value B</value>
    </researcher_keyword>
    <researcher_keyword>
        <value>Value C</value>
    </researcher_keyword>
   </researcher_keywords>
 </researcher>
</user>';

$oXML2 = new SimpleXMLElement( $s );
foreach($oXML2->researcher->researcher_keywords->researcher_keyword as $word){
    echo $word->value . '<br />';
}
  • Related