我知道如何使用PHP访问XML中的标签,但这一次,我必须使用函数getText($textId)
来访问这些标签中的文本内容,但我尝试了很多东西,我迫切需要帮助。
我试过这个
$doc->load("localisations_EN.xml");
$texts = $doc->getElementsByTagName("txt");
$elem = $doc->getElementById("home");
$children = $elem->childNodes;
foreach ($children as $child) {
if ($child->nodeType == XML_CDATA_SECTION_NODE) {
echo $child->textContent . "<br/>";
}
}
print_r($texts);
print_r($doc->getElementById('home'));
foreach ($texts as $text)
{
foreach($text->childNodes as $child) {
if ($child->nodeType == XML_CDATA_SECTION_NODE) {
echo $child->textContent . "<br/>";
}
}
}
然后我尝试了这个,但我不知道如何访问字符串值
$xml=simplexml_load_file("localisations_EN.xml") or die("Error: Cannot create object");
print_r($xml);
$description = $xml->xpath("//txt[@id='home']");
var_dump($description);
我得到了类似的东西
array(1){[0] =&gt; object(SimpleXMLElement)#2(1){[“@attributes”] =&gt; array(1){[“id”] =&gt; string(4)“home”}}}
这是我必须使用的XML文件
<?xml version="1.0" encoding="UTF-8" ?>
<localisation application="test1">
<part ID="menu">
<txt id="home"><![CDATA[Home]]></txt>
<txt id="news"><![CDATA[News]]></txt>
<txt id="settings"><![CDATA[Settings]]></txt>
</part>
<part ID="login">
<txt id="id"><![CDATA[Login]]></txt>
<txt id="password"><![CDATA[Password]]></txt>
<txt id="forgetPassword"><![CDATA[Forget password?]]></txt>
</part>
</localisation>
感谢您的帮助。
答案 0 :(得分:1)
simplexml元素有一个__toString()
魔术函数,它将返回元素的文本内容(但不是子元素的文本内容)
所以你的simplexml代码应该是
$xml=simplexml_load_file("localisations_EN.xml");
$description = (string) $xml->xpath("//txt[@id='home']")[0];
// ^-- triggers __toString() ^-- xpath returns array
因为xpath返回一个元素数组,你需要获取一个(或多个)并将其强制转换为字符串。获取该元素的直接内容。
不知道为什么要去那里的(不存在的)子节点。 CDATA只是语法说&#34;不解析这个,这是数据&#34;
$doc = new DOMDocument;
$doc->load("localisations_EN.xml");
$texts = $doc->getElementsByTagName('txt');
foreach($texts as $text) {
if($text->getAttribute('id') == 'home') {
// prepend hasAttribute('id') if needed to if clause above
$description = $text->textContent;
}
}
另外,$doc->getElementById()
可能只有在DTD将某个属性设置为ID时才有效。由于您的xml没有这样做(它没有命名DTD),因此它无法正常工作。
// $doc as before
$xpath = new DOMXPath($doc);
$description = $xpath->evaluate('//txt[@id="home"]')[0]->textContent;
// as before, xpath returns an array, that's why ---^