douying7289 2017-04-12 18:17
浏览 71
已采纳

PHP和XPath查询

I have an XML file similar to the text below:

<?xml version="1.0" standalone="yes"?>
<Calendar xmlns="urn:AvmInterchangeSchema-Calendario-1.0">
  <Date>
    <Day>12/04/2017</Day>
    <TypesDay>
      <Type>Test 1</Type>
      <Type>Test 2</Type>
      <Type>Test 3</Type>
    </TypesDay>
  </Date>
</Calendar>

And I am using this Xpath to select the nodes:

$xml = simplexml_load_file("file.xml");
$response = $xml->xpath('//*[text()="'.date("d/m/Y").'"]');

How can I take the "TypesDay" entries if that condition is met?

I hope not to create duplicates ... I'm going crazy for hours and it will definitely be a trivial thing.

  • 写回答

1条回答 默认 最新

  • doucai6663 2017-04-12 19:02
    关注

    There are a few approaches to do this. First of all, you should register the namespace:

    $xml->registerXPathNamespace('x', 'urn:AvmInterchangeSchema-Calendario-1.0');
    

    I'm assuming that your node name with the value 12/04/2017 could change.

    First

    Find a node called TypesDay inside the named namespace x that the parent node has a child node with value 12/04/2017

    $response = $xml->xpath('//*[*[text()="'.date("d/m/Y").'"]]/x:TypesDay');
    

    Second

    Find a node called TypesDay inside the named namespace x that is sibling of node with value 12/04/2017

    $response = $xml->xpath('//*[text()="'.date("d/m/Y").'"]/following-sibling::x:TypesDay');
    

    The result for both is:

    array(1) {
      [0]=>
      object(SimpleXMLElement)#2 (1) {
        ["Type"]=>
        array(3) {
          [0]=>
          string(6) "Test 1"
          [1]=>
          string(6) "Test 2"
          [2]=>
          string(6) "Test 3"
        }
      }
    }
    

    After all, if you want only the entries, just add the next level /x:Type:

    $response = $xml->xpath('//*[*[text()="'.date("d/m/Y").'"]]/x:TypesDay/x:Type');
    

    Or:

    $response = $xml->xpath('//*[text()="'.date("d/m/Y").'"]/following-sibling::x:TypesDay/x:Type');
    

    Result:

    array(3) {
      [0]=>
      object(SimpleXMLElement)#3 (1) {
        [0]=>
        string(6) "Test 1"
      }
      [1]=>
      object(SimpleXMLElement)#4 (1) {
        [0]=>
        string(6) "Test 2"
      }
      [2]=>
      object(SimpleXMLElement)#5 (1) {
        [0]=>
        string(6) "Test 3"
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致