PHP get a div from page x [duplicate]

2019-08-08 03:17发布

问题:

This question already has an answer here:

  • How do you parse and process HTML/XML in PHP? 30 answers

I wanna extract some html from page Y

for example site is
<head>xxxx</head>
<body>....<div id="ineedthis_code"> </div> ...</body>

it is possible to do this file_get_contents ?! i need only that div nothing else

回答1:

Without using a special library (which is the best way in most cases), you can use the explode-function:

$content = file_get_contents($url);
$first_step = explode( '<div id="YOUR ID HERE">' , $content ); // So you will get two array elements

$second_step = explode("</div>" , $first_step[1] ); // "1" depends, if you have more elements with this id (theoretical) 

echo $second_step[0]; // You will get the first element with the content within the DIV :)

Please note, it's only an example without error handling. It also works onlny on a special case; not if the html structure ist changing. Even simple spaces can break this code. So you should better use a parsing library ;-)