SimpleXML 提取 ID child 的文本
SimpleXML extract TEXT of ID child
我需要这个 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);
}
在 xml 中是 'zone',但在 php 中你有 'zona'。
array keys中不需要添加id和name属性,直接放标签名就可以了。
$info = "information: ".$array['trend']['zone']['subzone']['text'];
您不必将 SimpleXML 对象转换为数组即可访问其中的值,您可以像访问对象变量一样访问它们:
$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
echo $xml->trend->zone->subzone->text;
输出:
I want this text.
您可以使用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.
我需要这个 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);
}
在 xml 中是 'zone',但在 php 中你有 'zona'。 array keys中不需要添加id和name属性,直接放标签名就可以了。
$info = "information: ".$array['trend']['zone']['subzone']['text'];
您不必将 SimpleXML 对象转换为数组即可访问其中的值,您可以像访问对象变量一样访问它们:
$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
echo $xml->trend->zone->subzone->text;
输出:
I want this text.
您可以使用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.