node I am trying to parse various links from an xml file. I read the documents...">

Simple XML element: capture href inside <link rel = "alternate"> node

I am trying to parse various links from an xml file. I read the documents and every post I found about parsing XML files, but I did not find a way to access the nodes as I want. For instance:

<link rel="self" type="text/html" title="title0" length="8359" href="http://example0.com"/>
<link rel="alternate" type="text/html" title="title1" length="8359" href="http://example3.com"/>
<link rel="related" type="text/html" title="title2" length="8359" href="http://example4.com"/>
<link rel="related" type="text/html" title="title3" length="8359" href="http://example4.com"/>
<link rel="related" type="text/html" title="title4" length="8359" href="http://example5.com"/>
<link rel="related" type="text/html" title="title5" length="8359" href="http://example5.com"/>

How can I access:

  • A href reference that has rel = "self" (return String).
  • A href reference that has rel = "alternate" (return String).
  • hrefs of links having rel = "related" (return Array).

Using SimpleXML:

$xml=simplexml_load_file('url_to_xml') or die('Error: Cannot create object');

...

+4
source share
6 answers

" XML ". : - ; XPath .

, , SimpleXML :

  • $something['bar'] , (, <foo>) , (, bar="...")
  • (string)$something , SimpleXML

SimpleXML, foreach if , . , $xml <link>:

foreach ( $xml->link as $link ) {
    if ( $link['rel'] == 'self' ) {
        // Found <link rel="self">
        // assign to variable, return from function, etc
        // To access the attribute, we use $link['href']
        // To get the text content of the selected node,
        //   we cast to string with (string)$link['href']
        $self_link = (string)$link['href'];
    }
}

XPath :

  • //foo <foo>,
  • [bar] " " bar "
  • [@bar] ", " bar ",
  • [@bar="baz"] , "bar" "baz"

, //link[@rel="self"].

SimpleXML ->xpath() node . , :

$xpath_results = $xml->xpath('//link[@rel="self"]');
foreach ( $xpath_results as $node ) {
     // Again, we have a SimpleXMLElement object, and want 
     //    the string content of the 'href' attribute:
     $self_link = (string)$node['href'];
}
+1

XPath - XML-. SimpleXML . :

<?php
$string = <<<XML
<div>
  <link rel="self" type="text/html" title="title0" length="8359" href="http://example0.com"/>
  <link rel="alternate" type="text/html" title="title1" length="8359" href="http://example3.com"/>
  <link rel="related" type="text/html" title="title2" length="8359" href="http://example4.com"/>
  <link rel="related" type="text/html" title="title3" length="8359" href="http://example4.com"/>
  <link rel="related" type="text/html" title="title4" length="8359" href="http://example5.com"/>
  <link rel="related" type="text/html" title="title5" length="8359" href="http://example5.com"/>
</div>
XML;
$xml = new SimpleXMLElement($string);
foreach(['self', 'alternate', 'related', 'dne'] as $rel) {
  $val = @$xml->xpath("//link[@rel='$rel']/@href");
  $val = $val ? array_map(function($n) { return (string)$n; }, $val) : [];
  $val = count($val) == 1 ? $val[0] : $val;
  var_dump($val);
}
+4

xpath, , :

    <?php
    $string = <<<XML
    <div>
      <link rel="self" type="text/html" title="title0" length="8359" href="http://example0.com"/>
      <link rel="alternate" type="text/html" title="title1" length="8359" href="http://example3.com"/>
      <link rel="related" type="text/html" title="title2" length="8359" href="http://example4.com"/>
      <link rel="related" type="text/html" title="title3" length="8359" href="http://example4.com"/>
      <link rel="related" type="text/html" title="title4" length="8359" href="http://example5.com"/>
      <link rel="related" type="text/html" title="title5" length="8359" href="http://example5.com"/>
    </div>
    XML;

    $xml = new SimpleXMLElement($string);

    $related = [];

    foreach($xml->link as $link) {

        switch($link['rel']){
            case 'self':
                $self = $link['href'];
                break;
            case 'alternate':
                $alternate = $link['href'];
                break;
            case 'related':
                array_push($related, $link['href']);
                break;
        }

    }

    print $self;
    // outputs : http://example0.com

    print $alternate;
    // outputs : http://example3.com

    print_r($related);
    /* outputs : Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => http://example4.com
        )

    [1] => SimpleXMLElement Object
        (
            [0] => http://example4.com
        )

    [2] => SimpleXMLElement Object
        (
            [0] => http://example5.com
        )

    [3] => SimpleXMLElement Object
        (
            [0] => http://example5.com
        )

)
*/

switch, "if":

foreach($xml->link as $link) {
    if($link['rel'] == 'self'){
       $self = $link['href'];
    }
    if($link['rel'] == 'alternate'){
       $alternate = $link['href'];
    }
    if($link['rel'] == 'related'){
        array_push($related, $link['href']);
    }
}
+1

, if/switch, .

foreach($xml->getElementsByTagName('link') as $tag) {
   switch($tag->getAttribute('rel')) {
      case 'self':
         $href_of_self = $tag->getAttribute('href');
         break;
      case 'related':
         ...
   }
}

: http://php.net/manual/en/domdocument.getelementsbytagname.php http://php.net/manual/en/domelement.getattribute.php

0

http://sabre.io/xml, " XML PHP, ". parseCurrentElement() https://github.com/fruux/sabre-xml/blob/master/lib/Reader.php

class CustomXmlReader extends \Sabre\Xml\Reader {}
class CustomXmlService extends \Sabre\Xml\Service {}
0

, , , preg_match. , , , XML .

-3

All Articles