简体   繁体   中英

Find Specific Attribute Information Simple XML PHP

<resources>
<merchants count="7">
<merchant id="1300" name="Wal-M" count="1" logo_url="" url=""/>
<merchant id="1387" name="Nothing.com" count="1" logo_url="" url=""/>
<merchant id="3486" name="Micro" count="1" logo_url="" url=""/>
<merchant id="13880" name="Sea" count="1" logo_url="" url=""/>
<merchant id="13881" name="Kma" count="1" logo_url="" url=""/>
<merchant id="14711" name="Cas Interstate Music" count="1" logo_url="" url=""/>
<merchant id="1882969" name="Targ" count="1" logo_url="" url="http://r.url.com"/>
</merchants>

I have this xml file which return random number of merchant's every API call I always need the url attribute from the merchant with the name Targ

my code:

$fetchurl = "API URL"; $xml = simplexml_load_file($fetchurl); $merchantInfo=$xml->resources->merchant; <---stuck here how to get the url of Targ?

First off, you're xml isn't valid. It's missing the root closing </resources> .

Second you can just use SimpleXMLElement and use xpath and target Targ :

$data = '<resources><merchants count="7"><merchant id="1300" name="Wal-M" count="1" logo_url="" url=""/><merchant id="1387" name="Nothing.com" count="1" logo_url="" url=""/><merchant id="3486" name="Micro" count="1" logo_url="" url=""/><merchant id="13880" name="Sea" count="1" logo_url="" url=""/><merchant id="13881" name="Kma" count="1" logo_url="" url=""/><merchant id="14711" name="Cas Interstate Music" count="1" logo_url="" url=""/><merchant id="1882969" name="Targ" count="1" logo_url="" url="http://r.url.com"/></merchants></resources>';
$xml = new SimpleXMLElement($data);
$url = (string) $xml->xpath('//merchant[@name="Targ"]')[0]->attributes()->url;
echo $url; // http://r.url.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM