使用PHP从多行获取XML值(位置)

时间:2015-07-24 21:29:29

标签: php xml

我正在尝试使用php获取xml文件中的位置值:

 <?xml version="1.0" encoding="UTF-8" ?> 
 <GEC LOCATION="rm1" TECHNICIAN="19">
    <FIELDS>
        <FIELD ID="1" LABEL="ID:" VALUE="2" />
        <FIELD ID="9" LABEL="LOC:" VALUE="rm1" />
        <FIELD ID="22" LABEL="TECH:" VALUE="19" />
    </FIELDS>
 </GEC>

我的尝试:通过php

 $xml = simplexml_load_file('xml/file.xml');
 $getLocation = $xml->FIELD[LABEL];
 echo $getLocation;
 //this outputs only ID:

我想要抓住的是位置并尝试:

 $xml = simplexml_load_file('xml/file.xml');
 $getLocation = $xml->FIELDS[3]->FIELD[VALUE]; //or FIELD[LABEL]
 echo $getLocation;
 //this outputs nothing

我也试过从主要GEC获得

 $xml = simplexml_load_file('xml/file.xml');
 $getLocation = $xml->GEC[LOCATION];
 echo $getLocation;
 //nothing

我不确定我错过了什么。谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

这是使用XPath表达式作为选择器的一种可能方式:

$string = <<<XML
<GEC LOCATION="rm1" TECHNICIAN="19">
    <FIELDS>
        <FIELD ID="1" LABEL="ID:" VALUE="2" />
        <FIELD ID="9" LABEL="LOC:" VALUE="rm1" />
        <FIELD ID="22" LABEL="TECH:" VALUE="19" />
    </FIELDS>
 </GEC>
XML;
$xml = new SimpleXMLElement($string);
$getLocation = $xml->xpath("//FIELD[@LABEL='LOC:']/@VALUE")[0];
echo $getLocation;

<强> eval.in demo

关于正在使用的XPath的简要说明:

  • //FIELD:在XML文档中的任意位置查找<FIELD>个元素...
  • [@LABEL='LOC:']:...属性LABEL值等于LOC:
  • /@VALUE:从此类FIELD返回VALUE属性

输出

rml

答案 1 :(得分:0)

我从未使用过simplexml,所以这可能不是您想要的方式,但可以轻松修改以下内容以满足您的需求。

            $data='<?xml version="1.0" encoding="UTF-8" ?> 
             <GEC LOCATION="rm1" TECHNICIAN="19">
                <FIELDS>
                    <FIELD ID="1" LABEL="ID:" VALUE="2" />
                    <FIELD ID="9" LABEL="LOC:" VALUE="rm1" />
                    <FIELD ID="22" LABEL="TECH:" VALUE="19" />
                </FIELDS>
             </GEC>';


            libxml_use_internal_errors( TRUE );
            $dom = new DOMDocument('1.0','utf-8');
            $dom->validateOnParse=false;
            $dom->standalone=TRUE;
            $dom->preserveWhiteSpace=TRUE;
            $dom->strictErrorChecking=false;
            $dom->substituteEntities=FALSE;
            $dom->recover=TRUE;
            $dom->formatOutput=false;

            /* Rather than loading the xml from a static string
               you might wish to use the following instead:- 
             $dom->loadXML( file_get_contents('path/to/file.xml') );
            */
            $dom->loadXML( $data );
            $parse_errs=serialize( libxml_get_last_error() );
            libxml_clear_errors();


            $col=$dom->getElementsByTagName('FIELD');
            foreach( $col as $node ) echo $node->getAttribute('ID').' '.$node->getAttribute('LABEL').' '.$node->getAttribute('VALUE').'<br />';
            $dom=null;


            /* Will print out */
            /*
             1 ID: 2
             9 LOC: rm1
             22 TECH: 19
            */