2015-03-02 5 views
1

из этого ответа XML data extraction using PHP simpleXMLXML дочерние узлы в XPATH SimpleXMLElement

Я до сих пор возникают проблемы извлечения дочерних узлов, используя XPath. Раньше в некотором контексте я использовал ->children();, который мне помог, но пока на xpath я не могу использовать children(); Я также попытался использовать //, чтобы узнать, может ли это получить все содержимое дочерних узлов, но все равно не повезло.

Мой PHP код

$xml = simplexml_load_string(file_get_contents($fileloc)); 
$json = json_encode($xml); 
$array = json_decode($json,TRUE); 
$node = $xml->xpath('//Note[@id="f2"]/P'); 
$array = json_decode(json_encode($node), true); 
print_r($array); 

Кроме того, как можно напечатать только выход? Я пробовал использовать для каждого цикла эхо, но это не сработало.

, когда я использую print_r его отображения в качестве Array ([0] => Array ([Pubref] => []))

Моя структура XML похожа

<Notes> 
    <Note id="f1" type="foot" display="1"> 
     <P>The second respondent by virtue of the extended definition of “foreign state” in s 3(3) of the Act.</P> 
    </Note> 
    <Note id="f2" type="foot" display="2"> 
     <P> 
      <Pubref>[<Year>1965</Year>] <Series>VR</Series><Pages>204</Pages></Pubref>.</P> 
    </Note> 
    <Note id="f3" type="foot" display="3"> 
     <P>Ibid, 206.</P> 
    </Note> 
    <Note id="f4" type="foot" display="4"> 
     <P> 
      <Emph type="i">Foreign State Immunity</Emph>, ALRC 24, (1984).</P> 
    </Note> 
    <Note id="f5" type="foot" display="5"> 
     <P>Ibid, 55, [93].</P> 
    </Note> 
    <Note id="f6" type="foot" display="6"> 
     <P>Macquarie Dictionary (5th ed, 2009), 1475.</P> 
    </Note> 
    <Note id="f7" type="foot" display="7"> 
     <P>Ibid, 727.</P> 
    </Note> 
    <Note id="f8" type="foot" display="8"> 
     <P> 
      <Emph type="i">Foreign State Immunity</Emph>, ALRC 24, 1984, p xviii, [17] and p 51, [90].</P> 
    </Note> 
    <Note id="f9" type="foot" display="9"> 
     <P> 
      <Pubref>(<Year>2011</Year>) <Vol>192</Vol><Series>FCR</Series><Pages>393</Pages></Pubref>.</P> 
    </Note> 
    <Note id="f10" type="foot" display="10"> 
     <P>Ibid, 437.</P> 
    </Note> 
    <Note id="f11" type="foot" display="11"> 
     <P> 
      <Pubref>(<Year>2004</Year>) <Vol>185</Vol><Series>FLR</Series><Pages>48</Pages></Pubref>.</P> 
    </Note> 
    <Note id="f12" type="foot" display="12"> 
     <P>Ibid, [108].</P> 
    </Note> 
    <Note id="f13" type="foot" display="13"> 
     <P>(2005) 12 VR 340, 346.</P> 
    </Note> 
    <Note id="f14" type="foot" display="14"> 
     <P> 
      <Pubref>[<Year>1987</Year>] <Vol>1</Vol><Series>Qd R</Series><Pages>221</Pages></Pubref>.</P> 
    </Note> 
    <Note id="f15" type="foot" display="15"> 
     <P> 
      <MNCit>[2008] QCA 328</MNCit>.</P> 
    </Note> 
    <Note id="f16" type="foot" display="16"> 
     <P> 
      <Pubref>[<Year>2013</Year>] <Vol>1</Vol><Series>Qd R</Series><Pages>204</Pages></Pubref>.</P> 
    </Note> 
    <Note id="f17" type="foot" display="17"> 
     <P>[1955] AC 72.</P> 
    </Note> 
    <Note id="f18" type="foot" display="18"> 
     <P> 
      <Pubref>(<Year>1988</Year>) <Vol>17</Vol><Series>NSWLR</Series><Pages>623</Pages></Pubref>.</P> 
    </Note> 
    <Note id="f19" type="foot" display="19"> 
     <P> 
      <Pubref>(<Year>2010</Year>) <Vol>79</Vol><Series>NSWLR</Series><Pages>513</Pages></Pubref>.</P> 
    </Note> 
    <Note id="f20" type="foot" display="20"> 
     <P>[1955] AC 72, 87.</P> 
    </Note> 
    <Note id="f21" type="foot" display="21"> 
     <P>Ibid, 89–90.</P> 
    </Note> 
    <Note id="f22" type="foot" display="22"> 
     <P> 
      <Pubref>(<Year>1988</Year>) <Vol>17</Vol><Series>NSWLR</Series><Pages>623</Pages></Pubref>, 630.</P> 
    </Note> 
    <Note id="f23" type="foot" display="23"> 
     <P> 
      <Pubref>(<Year>2010</Year>) <Vol>79</Vol><Series>NSWLR</Series><Pages>513</Pages></Pubref>.</P> 
    </Note> 
    <Note id="f24" type="foot" display="24"> 
     <P> 
      <Pubref>(<Year>1988</Year>) <Vol>17</Vol><Series>NSWLR</Series><Pages>623</Pages></Pubref>, 633 per Cole J cited in <Xref ref="cr11" role="cr"><Name><Emph type="i">Zhang v Zemin</Emph></Name><Pubref>(<Year>2010</Year>) <Vol>79</Vol><Series>NSWLR</Series><Pages>513</Pages></Pubref>, 524</Xref>.</P> 
    </Note> 
    <Note id="f25" type="foot" display="25"> 
     <P> 
      <Pubref>[<Year>1983</Year>] <Vol>1</Vol><Series>AC</Series><Pages>244</Pages></Pubref>.</P> 
    </Note> 
    <Note id="f26" type="foot" display="26"> 
     <P> 
      <Pubref>(<Year>2012</Year>) <Vol>247</Vol><Series>CLR</Series><Pages>240</Pages></Pubref>.</P> 
    </Note> 
    <Note id="f27" type="foot" display="27"> 
     <P> 
      <Pubref>[<Year>1983</Year>] <Vol>1</Vol><Series>AC</Series><Pages>244</Pages></Pubref>, 262.</P> 
    </Note> 
    <Note id="f28" type="foot" display="28"> 
     <P>At [23].</P> 
    </Note> 
</Notes> 
+0

[xpath()] (http://php.net/manual/en/simplexmlelement.xpath.php) должен возвращать [SimpleXMLElement] (http://php.net/manual/en/simplexmlelement.xpath.php), который имеет метод [children()] (http://php.net/manual/en/simplexmlelement.children.php) для извлечения детей, поэтому вы должны иметь возможность использовать его – Phate01

+0

@ Phate01 - Затем почему он возвращает только 'Array ([0] => Array ([Pubref] => [])), тогда как узел' Pubref' в 'id = 'f2'' имеет дочерние' Year, Series, Pages' – user4568438

+0

Вы, re превращая полезный объект SimpleXMLElement в менее полезный массив (с 'json_decode (json_encode())' hack), а затем сбрасывая массив. Просто используйте SimpleXML [в том виде, в котором он предназначен] (http://www.php.net/manual/en/simplexml.examples-basic.php). – IMSoP

ответ

1

Вы не можете просто использовать json_encode в списке xmlelement, который вы получите с помощью xpath. Список xmlelement представляет собой массив xmlelements. И json_encode заставляет элементы xml делать ->__toString(), возвращая только тексты непосредственно внутри элемента. (И не из дочерних элементов.)

Итак, в вашем примере код вернет . с некоторыми пробелами, так как ваш xpath возвращает список xmlelement всего с одним элементом (<p>) и имеет только дочерние элементы и некоторый текст (пробелы и .)

Чтобы получить внутреннюю XML элементов, вы должны использовать ->asXML():

$xml = simplexml_load_string($xmlstring); 
$elements = $xml->xpath('//Note[@id="f2"]/P'); 
foreach ($elements as $element) { 
    echo $element->asXML(); 
} 

Печатается:

<P><Pubref>[<Year>1965</Year>] <Series>VR</Series> <Pages>204</Pages></Pubref>.</P> 
+0

Таким образом, вы не можете обрабатывать отдельные дочерние узлы, потому что вы их не анализируете – Phate01

+1

@ Phate01 Я не думаю, что это намерение OP. Но если OP хотел бы иметь дочерние узлы отдельно, он должен изменить свой запрос xpath. '// Примечание [@ id =" f2 "]/P/*' –

+0

Вот что мне не хватало, чтобы обеспечить как ООП, так и не ООП – Phate01

1

Просто раздеться квадратные скобки, что окружает <year> ребенка, и это работает для меня:

$xml = new SimpleXMLElement(
'<Notes> 
    <Note id="f1" type="foot" display="1"> 
     <P>The second respondent by virtue of the extended definition of [...] in s 3(3) of the Act.</P> 
    </Note> 
    <Note id="f2" type="foot" display="2"> 
     <P> 
      <Pubref><Year>1965</Year> <Series>VR</Series><Pages>204</Pages></Pubref>.</P> 
    </Note> 
    [....] 
</Notes>'); 

$array = $xml->xpath("/Notes/Note[@id=\"f2\"]/P"); 
var_dump($array[0]->children()); 

Отпечатано

object(SimpleXMLElement)#3 (1) { 
    ["Pubref"]=> 
    object(SimpleXMLElement)#5 (3) { 
    ["Year"]=> 
    string(4) "1965" 
    ["Series"]=> 
    string(2) "VR" 
    ["Pages"]=> 
    string(3) "204" 
    } 
} 

Чтобы показать результаты, просто сделать еще один ->children(), чтобы получить те, что вам нужно, и использовать Еогеасп:

$array = $xml->xpath("/Notes/Note[@id=\"f2\"]/P"); 
$children = $array[0]->children()->children(); 

foreach($children as $k => $v) 
    echo "[$k] => $v"; 

EDIT: Как было предложено @ п-х, для того, чтобы держать скобки вы можете просто обновите свой xpath таким образом: "/Notes/Note[@id=\"f2\"]/P/*". Затем в ->children() у вас будут все необходимые вам узлы

+0

Я оставил тег '' без форматирования в качестве кода, не было видно – Phate01

+0

Это работает, если вы снимаете скобки круглый год. – Phate01

+0

yep, gotcha bro. Спасибо :) – user4568438

Смежные вопросы