0

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

1
  • I think you need to loop over $oXML2->researcher->researcher_keywords->children() Commented Oct 21, 2021 at 19:39

1 Answer 1

2

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 />';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks u_mulder! You rock!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.