skip to Main Content

I need the text of the of the of this xml file to use it in telegram, if the xml cames without “id” and “name” i can do it, but no with the tags

<root>
<origen>...</origen>
<trend>
    <zone id="809" name="AGi">
      <subzone id="809" name="AGi">
        <text>
          I want this text.
        </text>
      </subzone>
    </zone>
</trend>
function getIdTEXT($chatId){
    $context = stream_context_create(array('http' =>  array('header' => 'Accept: application/xml')));
    $url = "http://www.thexmlfile/MM.xml";

    $xmlstring = file_get_contents($url, false, $context);

    $xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
    $json = json_encode($xml);
    $array = json_decode($json, TRUE);

    $info = "information: ".$array['trend']['zona id="809" nama="AGi"']['subzone id="809" nombre="AGi"']['text'];

    sendMessage($chatId, $info);
}

3

Answers


  1. In xml is ‘zone’, but in php you have ‘zona’.
    You not need to add the id and name attributes in array keys, just put the tag name.

    $info = "information: ".$array['trend']['zone']['subzone']['text'];
    
    Login or Signup to reply.
  2. You don’t have to convert your SimpleXML object to an array to access values from it, you can just access them like object variables:

    $xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
    echo $xml->trend->zone->subzone->text;
    

    Output:

    I want this text.
    

    Demo on 3v4l.org

    Login or Signup to reply.
  3. You can use XPath to query the exact node you want :

    $xml = simplexml_load_string($xmlstring);
    $nodes = $xml->xpath("/root/trend/zone[@id = 809 and @name= 'AGi']/subzone[@id = 809 and @name = 'AGi']/text") ;
    $text = (string)$nodes[0] ;
    echo $text ; // I want this text.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search