简体   繁体   中英

PHP SimpleXMLElement XPath Selection

I have the following XML: http://pastebin.com/QiRK72BK

which is generated in response to a REST query. My code is very simple:

$xml = simplexml_load_file($url);

var_dump($xml->getName());

var_dump($xml->xpath("serverDetail/apiEnv"));

in an attempted test case. The first var_dump reveals that the XML file is indeed being loaded:

 string(21) "GeneralSearchResponse"

However, the second var_dump puzzles me. I feel it should definitely match some data, but instead I get

array(0) { }

I've also tried the xpath "/serverDetail/apiEnv" "//apiEnv" and "/" and always get an empty array. Am I misunderstanding xpath or perhaps missing some initialization step?

Your XML is using a namespace:

$xml->registerXPathNamespace('u', 'urn:types.partner.api.shopping.com');
var_dump($xml->xpath("//u:serverDetail/u:apiEnv"));

Output:

array(1) {
  [0]=>
  object(SimpleXMLElement)#2 (1) {
    [0]=>
    string(7) "sandbox"
  }
}

Edit: Dirty workaround, might be helpful though:

$xml = simplexml_load_file($url);
$xmlStr = str_replace("xmlns", "ns", $xml->asXML());
$xml = new SimpleXMLElement($xmlStr);
var_dump($xml->xpath("serverDetail/apiEnv"));

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