Search code examples
phparraysparsingsimplexmlcurly-brackets

PHP SimpleXML to JSON Encode single element array


I am trying to parse xml with php into a single element json array.

This is what I have:

$t = array();

$a=array("url"=>$test->channel->item->link);
array_push($t,$a);
echo json_encode($t);;

Which gives me this:

[{"url":{"0":"http:www.example.com"}}]

But I am looking for this:

[{"url":"http:www.example.com"}]

It seems that $test->channel->item->link parses with curly brackets as {url}

but if I do echo $test->channel->item->link, I get: www.example.com without the curly brackets.


Solution

  • Not sure if this is what you're looking for, but it works :)

    $xmlstr = '<?xml version=\'1.0\' standalone=\'yes\'?>
          <container>
            <channel>
              <item>
                <link>www.example.com</link>
              </item>
            </channel>
          </container>';
    
    $test = new SimpleXMLElement($xmlstr);
    
    $t = array();
    $a = array("url"=>$test->channel->item->link->__toString());
    array_push($t,$a);
    echo json_encode($t); // [{"url":"www.example.com"}]