如何按属性从xml文件中选择数据?

时间:2014-01-17 14:01:20

标签: php xml

这是我的xml文件note.xml文件

<?xml version="1.0" encoding="ISO-8859-1"?>
<agents>
    <agent>
    <id>1</id>
    <image> img/primary-nav-logo.png</image>
    <name>Tommy Jenkin</name>
    <company>CJenkins Insurance</company>
    <street>Insurance150 S State Stree</street>
    <city>Linkend</city>
    <phone>(773) 561-4331</phone>
    </agent>
    <agent>
    <id>2</id>
    <image> img/primary-nav-logo.png</image>
    <name>Tommy Jenkin</name>
    <company>CJenkins Insurance</company>
    <street>Insurance150 S State Stree</street>
    <city>Linkend</city>
    <phone>(773) 561-4331</phone>
    </agent>
</agents>

我必须打印id 1的xml记录,我在这里写了代码

<?php
    $xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
    foreach($xml->xpath('//agent') as $item) { 
    $row = simplexml_load_string($item->asXML());
    $v = $row->xpath('//id[. ="1"]');
    if($v[0]){ 
        print $item->id; 
        print $item->image; 
        print $item->name; 
        print $item->company; 
        print $item->street; 
        print $item->city;
        print $item->phone; 
    }
    else{
        echo 'No records';
    }
?>

请建议我在哪里错了

2 个答案:

答案 0 :(得分:0)

你有几种方法,这是其中之一

$xml = new DOMDocument();
$xml->loadXML($input);
$agents= $xml->getElementsByTagName("agent");
foreach ($agents as $agent) {
    $elements = $xml->getElementsByTagName("id");
    $id = $elements->item(0)->nodeValue;
}

答案 1 :(得分:0)

太复杂了,这样做:

$xml = simplexml_load_file("note.xml") or die("Error: Cannot create object");
$results = "/agents/agent[id = '1']";
foreach($results as $item) { 

    print $item->id; 
    print $item->image; 
    // etc        
}