使用PHP访问XML中元素的值

时间:2016-02-02 05:01:06

标签: php xml xpath

我正在尝试使用以下内容访问xml文件

<?xml version="1.0" encoding="UTF-8"?>
<descriptions> 
  <image> 
    <name>1.jpg</name>  
    <text>Investor Return</text> 
  </image> 
</descriptions>

如何检索&#34; text&#34;的值?为&#34;名称&#34; = 1.jpg?我试过使用$desc = $xml->xpath('image[name="'.$file.'"]/text'); 但它给出一个包含单个simplexmlelement(无值)的数组。有人可以提出解决方案吗?

由于

萨钦

1 个答案:

答案 0 :(得分:0)

尝试使用//image而不只是image(尽管您的原始XPath也适用于我,请参阅演示here):

$raw = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<descriptions> 
  <image> 
    <name>1.jpg</name>  
    <text>Investor Return</text> 
  </image> 
</descriptions>
XML;
$file = "1.jpg";
$xml = simplexml_load_string($raw);
$result = $xml->xpath('//image[name="'.$file.'"]/text');
echo $result[0];

<强> eval.in demo

输出

Investor Return