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


Get XML Value (Location) from multiple rows using PHP

我正在尝试使用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>

My try: through 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

我不知道我错过了什么。谢谢你的帮助!

这是使用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:查找<FIELD>元素(s),在XML文档的任何地方…
  • [@LABEL='LOC:']:…属性LABEL的值等于LOC:
  • /@VALUE:从FIELD返回VALUE属性
输出:

rml

我从来没有使用过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
            */