SimpleXML提取ID子的TEXT

问题描述 投票:-1回答:3

我需要这个xml文件的文本在电报中使用它,如果xml没有“id”和“name”我可以做到,但没有标签

<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);
}
php simplexml telegram-bot
3个回答
2
投票

您可以使用XPath查询所需的确切节点:

$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.

1
投票

您不必将SimpleXML对象转换为数组以从中访问值,您只需像对象变量一样访问它们:

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

输出:

I want this text.

Demo on 3v4l.org


0
投票

在xml中是'zone',但在php中你有'zona'。您不需要在数组键中添加id和name属性,只需添加标记名称即可。

$info = "information: ".$array['trend']['zone']['subzone']['text'];
© www.soinside.com 2019 - 2024. All rights reserved.