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"
      }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊